【问题标题】:(cannot find) python countable attribute most_common()(找不到)python 可数属性 most_common()
【发布时间】:2017-01-19 12:10:16
【问题描述】:

这里是新手。我正在浏览 nltk 书和另一本 Python 介绍书。 我早些时候在 nltk 书中遇到了 most_common() ,虽然当时我无法让它工作也没有找到解决方案,但我创建了一个小函数,在那个特定的练习中完成了这个技巧并继续前进。 现在我又需要它了,但我认为我不能轻易解决它(练习是关于特定文本中最常见的单词长度),而且我知道我会在后面的示例中再次找到它,并且我希望能够跟随,因为正如我所说,我是新手。

理论上,我应该可以这样做:

fdist = FreqDist(len(w) for w in text1)

fdist.most_common()
[(3, 50223), (1, 47933), (4, 42345), (2, 38513) ...

但是,Python 告诉我:

AttributeError: 'FreqDist' object has no attribute 'most_common'

我发现 most_common() 是计数器对象 (http://docs.python.org/2/library/collections.html) 和 (http://docs.python.org/dev/library/collections#collections.Counter) 的一个属性。我知道也许我应该导入一些东西(一个模块?),但是我尝试导入的东西要么不起作用(未定义或不存在的消息),要么不包含它 - 我试过了

import collections 

那里没有错误,但是当我输入 dir(collections) 或 dir(builtins) 时没有列出 most_common()。

我安装了 2.7 和 3.0(大部分时间是 Windows,偶尔在我的虚拟机中使用 ubuntu 工作)。我会继续搜索,但非常感谢您的意见。这感觉有点基本,但我正在学习,至少现在我自己也搞不清楚。 再次,非常感谢。

【问题讨论】:

    标签: python python-2.7 python-3.x nltk


    【解决方案1】:

    nltk.probability.FreqDist 不是collections.Counter

    使用items 方法获取按排序顺序排列的项目列表(最常见的在前)。

    >>> from nltk.probability import FreqDist
    >>> dist = FreqDist([1, 2, 1, 2, 1])
    >>> dist.items()
    [(1, 3), (2, 2)]
    

    或者直接使用collections.Counter:

    >>> from collections import Counter
    >>> c = Counter([1, 2, 1, 2, 1])
    >>> c.most_common()
    [(1, 3), (2, 2)]
    

    【讨论】:

    • 非常感谢,这对本练习和上一个练习都有效。我仍然想知道为什么他们在书中使用 most_common() 作为名称 - 后来更改了它,所以它不会与 collections.Counter 混淆?。
    • 因为在Counter.most_common 中实现了相同的功能。 c = Counter(some_list); c.most_common(:10) == fd = FreqDist(some_list); fd.most_common(:10)
    【解决方案2】:

    一些旧版本的 nltk 没有most_common 模块。这可以通过打印dir(fdist)来验证。

    如果没有找到,只需使用pip升级nltk版本如下:

    sudo pip install -U nltk

    它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多