Python nltk统计单词和短语频率

标签 python nltk word-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 个长度的短语,而无需复制此代码仅更改计数变量?

最佳答案

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

相关文章:

python - 端口.h : No such file or directory

python - NLTK - block 语法不读取逗号

python - Django - 用户地理定位

python - 如何使 Django 1.7.1 在 Python 3.4.2 中可见?

python - 训练两个特征而不是一个

python - 在 nltk 树中,我如何从 child 访问 parent ?

c++ - 词频程序-文件输入太大?

python - 如何构建 pandas 数据框中项目的频率计数表?

sorting - 如何(如果可能)在 Rust 中按值对 BTreeMap 进行排序?

python - 尽管两个查询集在 shell 中打印出相同的内容,但 Django 的 assertQuerysetEqual() 方法还是失败了?