我正在使用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)
这部分是我要找的。
我的问题是,有没有一种更方便的方法来做到这一点,不重复这段代码,只改变计数变量,就可以说是4或5个短语的长度?
既然您标记了这个
nltk
,下面介绍如何使用nltk
的方法来完成此任务,这些方法比标准python集合中的方法具有更多的功能。字典中的每个元素都是ngram频率的字典。例如,您可以得到五个最常见的三联图,如下所示:
是的,不要运行这个循环,使用
collections.Counter(bigrams)
或pandas.Series(bigrams).value_counts()
来计算一行中的计数。相关问题 更多 >
编程相关推荐