python中文词组统计次数_Python nltk计数单词和短语频率

我正在使用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的短语,而不重复此代码只是为了更改计数变量?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值