我正在使用NLTK并试图让单词短语数达到特定文档的特定长度以及每个短语的频率。我将字符串标记为获取数据列表。Python 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的短语,而不重复此代码只是为了更改计数变量?