在 'compat.py' 中找不到参考 'Counter'

Cannot find reference 'Counter' in 'compat.py'

我正在尝试 运行 我从 here 获得的 nltk 的 BLEU 分数计算模块。但是我收到以下导入错误。

from nltk.compat import Counter

我尝试了计数器的 pip 安装,它已成功安装。我在这个项目中使用了相同的解释器。但这仍然显示为错误。

Cannot find reference 'Counter' in 'compat.py'

我正在使用 Python 3.5 并在 pycharm 中工作。

对于解决此问题的任何建议,我们将不胜感激。

关于您的 nltk 版本,您所关注的文档已过时。

There used to be Counter classcollections 导入 compat.py 并且 nltk.align.bleu 模块正在导入它,就好像它是在 compat.py 中定义的一样。

现在不再是 nltk.align.bleu,而是 nltk.translate.bleu,您可能还想使用 up-to-date documentation

为了完整起见,pip install Counter 将从 Python 2.7.

开始将 Counter third party library (than can then be imported as counter.Counter) that supports Python2 only and should be used only on Python2.6 and earlier now (if anyone still use those). It has been incorporated into the standard library 安装为 collections.Counter

TL;DR

您的 nltk 版本已过时。请升级。

pip install -U nltk

当前版本应该是3.3。 3.0 版本太旧了。

虽然我的 nltk 版本是最新的并且我使用的是 Python 3.5,但我一直收到以下错误。

Cannot find reference 'Counter' in 'compat.py'

这不是 问题 compat.py 文件,而是 无法解析计数器对象。由于 Counter 是一个用于计算可哈希对象的字典 subclass,我尝试使用 python 导入它 collections module.These 是高性能容器数据 types.This 可从 Python 2.7 获得。

所以我简单地修改了导入语句如下,它起作用了。

from collections import Counter

还有几个 pointers on Counters:它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。计数可以是任何整数值,包括零或负计数。 Counter class 类似于其他语言中的 bags 或 multi-sets。