Python nltk计算单词和短语频率

2024-05-17 08:09:19 发布

您现在位置: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个短语的长度?


Tags: 代码infromtestimportdataisnot
2条回答

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

字典中的每个元素都是ngram频率的字典。例如,您可以得到五个最常见的三联图,如下所示:

all_counts[3].most_common(5)

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

相关问题 更多 >