我正在使用 NLTK 并尝试让特定文档的单词短语计数达到一定长度以及每个短语的频率。我标记字符串以获取数据列表。
from nltk.util import ngrams
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.collocations import *
data = ["this", "is", "not", "a", "test", "this", "is", "real", "not", "a", "test", "this", "is", "this", "is", "real", "not", "a", "test"]
bigrams = ngrams(data, 2)
bigrams_c = {}
for b in bigrams:
if b not in bigrams_c:
bigrams_c[b] = 1
else:
bigrams_c[b] += 1
上面的代码给出并输出如下:
(('is', 'this'), 1)
(('test', 'this'), 2)
(('a', 'test'), 3)
(('this', 'is'), 4)
(('is', 'not'), 1)
(('real', 'not'), 2)
(('is', 'real'), 2)
(('not', 'a'), 3)
这部分是我正在寻找的。p>
我的问题是,是否有一种更方便的方法可以说出最多 4 或 5 个长度的短语,而无需复制此代码仅更改计数变量?
最佳答案
既然你标记了这个 nltk
,下面是如何使用 nltk
的方法来完成它,它比标准 python 集合中的方法有更多的特性。
from nltk import ngrams, FreqDist
all_counts = dict()
for size in 2, 3, 4, 5:
all_counts[size] = FreqDist(ngrams(data, size))
字典 all_counts
的每个元素都是 ngram 频率的字典。例如,您可以像这样得到五个最常见的八卦:
all_counts[3].most_common(5)
关于Python nltk统计单词和短语频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40669141/