Python nltk 统计单词和短语频率

Python nltk counting word and phrase frequency

我正在使用 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 个长度的短语,而无需复制此代码仅更改计数变量?

是的,不要 运行 这个循环,使用 collections.Counter(bigrams)pandas.Series(bigrams).value_counts() 来计算一行中的计数。

既然你标记了这个 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)