无法让Counter()在python中工作

时间:2013-05-28 23:02:53

标签: python

我正在尝试制作一个使用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

我得到一个空柜台。我该如何修补? 在早期版本中,我确实获得了数据,但它一直在计算迭代次数(在实际程序中,文本是不同文件的集合)。 有没有人有想法?

1 个答案:

答案 0 :(得分:2)

我们在那里放一些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})