回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在使用NLTK,并试图使单词短语计数到特定文档的特定长度以及每个短语的频率。我标记字符串以获取数据列表。</p>
<pre><code>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
</code></pre>
<p>上面的代码给出并输出如下:</p>
<pre><code>(('is', 'this'), 1)
(('test', 'this'), 2)
(('a', 'test'), 3)
(('this', 'is'), 4)
(('is', 'not'), 1)
(('real', 'not'), 2)
(('is', 'real'), 2)
(('not', 'a'), 3)
</code></pre>
<p>这部分是我要找的。</p>
<p>我的问题是,有没有一种更方便的方法来做到这一点,不重复这段代码,只改变计数变量,就可以说是4或5个短语的长度?</p>