Skip to main content
 首页 » 编程设计

python之NLTK 创建带有句子边界的双字母组

2025年02月15日13yxwkf

我正在尝试使用不跨越句子边界的 nltk 创建双字母组。我尝试使用 from_documents,但是它并没有像我希望的那样工作。

import nltk 
from nltk.collocations import * 
bigram_measures = nltk.collocations.BigramAssocMeasures() 
 
finder = BigramCollocationFinder.from_documents([['This', 'is', 'sentence', 'one'], ['A', 'second', 'sentence']]) 
print finder.nbest(bigram_measures.pmi, 10) 
 
>> [(u'A', u'second'), (u'This', u'is'), (u'one', u'A'), (u'is', u'sentence'), (u'second', u'sentence'), (u'sentence', u'one')] 

这包括 (u'one', u'A'),这是我试图避免的。

请您参考如下方法:

我最终放弃了 nltk 并手动进行处理:

为了创建 ngram,我在 http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/ 上找到了这个方便的函数

def find_ngrams(input_list, n): 
    return zip(*[input_list[i:] for i in range(n)]) 

从那里,我通过执行以下操作计算了二元概率:

首先我创建了双字母组

all_bigrams = [find_ngrams(sentence, 2) for sentence in text] 

然后我把它们按第一个词分组

first_words = {} 
for bigram in all_bigrams: 
    if bigram[0] in first_words.keys(): 
        first_words[bigram[0]].append(bigram) 
    else: 
        first_words[bigram[0]] = [bigram] 

然后我计算了每个二元组的概率

bi_probabilites = {} 
for bigram in (set(all_bigrams)): 
    bigram_count = 0 
    first_word_list = first_words[bigram[0]] 
    for item in first_word_list: 
        if item == bigram: 
            bigram_count += 1 
    bi_probabilites[bigram] = { 
        'count': bigram_count,  
        'length': len(first_word_list),  
        'prob': float(bigram_count)/len(first_word_list) 
    } 

不是最优雅的,但它完成了工作。