python - 无法让 Counter() 在 python 中工作

标签 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

我得到了一个空柜台。我该如何解决这个问题? 在早期版本中,我确实取回了数据,但它一直在迭代中计数(在实际程序中,文本是不同文件的集合)。 有人有想法吗?

最佳答案

让我们在其中添加一些 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/

相关文章:

python - openerp 安排服务器 Action

python - 在一行中创建多个字典而不引用其他字典?

python - 在 python3 请求中传递参数而不转义

python - 如何减少Python3请求中连接超时的等待?

python - Pyqt5多线程错误:QObject::connect:无法对类型 'QTextCursor'的参数进行排队

python - 如何在 Python 中检查 wget/urllib2 的结果?

python - 计算 numpy 数组之间的距离

python - JSON(列表,不是字典)到 csv 文件 - PYTHON

python - 在 Python 函数中使用输入语句作为参数

python - 用于触摸屏设备的 pygtk