我正在尝试使用不跨越句子边界的 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)
    }

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

关于python - NLTK 创建具有句子边界的二元组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40879616/

10-12 23:27