我正在尝试制作一个计数器,它使用 POS 三元组列表来检查大量三元组并找到它们的频率。 到目前为止我的代码如下:
from nltk import trigrams
from nltk.tokenize import wordpunct_tokenize
from nltk import bigrams
from collections import Counter
import nltk
text= ["This is an example sentence."]
trigram_top= ['PRP', 'MD', 'VB']
for words in text:
tokens = wordpunct_tokenize (words)
tags = nltk.pos_tag (tokens)
trigram_list=trigrams(tags)
list_tri=Counter (t for t in trigram_list if t in trigram_top)
print list_tri
我得到了一个空柜台。我该如何解决这个问题? 在早期版本中,我确实取回了数据,但它一直在迭代中计数(在实际程序中,文本是不同文件的集合)。 有人有想法吗?
最佳答案
让我们在其中添加一些 print
来进行调试:
from nltk import trigrams
from nltk.tokenize import wordpunct_tokenize
from nltk import bigrams
from collections import Counter
import nltk
text= ["This is an example sentence."]
trigram_top= ['PRP', 'MD', 'VB']
for words in text:
tokens = wordpunct_tokenize (words)
print tokens
tags = nltk.pos_tag (tokens)
print tags
list_tri=Counter (t[0] for t in tags if t[1] in trigram_top)
print list_tri
#['This', 'is', 'an', 'example', 'sentence', '.']
#[('This', 'DT'), ('is', 'VBZ'), ('an', 'DT'), ('example', 'NN'), ('sentence', 'NN'), ('.', '.')]
#Counter()
请注意,list=
部分是多余的,我已更改生成器以仅采用单词而不是 pos 标记
我们可以看到没有一个 pos 标签直接匹配您的 trigram_top - 您可能需要修改比较检查以适应 VB/VBZ...
可能会更改线路:
list_tri=Counter (t[0] for t in tags if t[1].startswith(tuple(trigram_top)))
# Counter({'is': 1})
关于python - 无法让 Counter() 在 python 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802902/