gpt4 book ai didi

python - Python 的 collections.Counter 和 nltk.probability.FreqDist 之间的区别

转载 作者:太空狗 更新时间:2023-10-30 00:49:01 28 4
gpt4 key购买 nike

我想计算文本语料库中单词的词频。我一直在使用 NLTK 的 word_tokenize 后跟 probability.FreqDist 一段时间来完成这项工作。 word_tokenize 返回一个列表,该列表由 FreqDist 转换为频率分布。然而,我最近遇到了集合中的计数器函数 (collections.Counter),它似乎在做完全相同的事情。 FreqDist 和 Counter 都有一个 most_common(n) 函数,它返回 n 个最常见的单词。有谁知道这两者之间是否有区别?一个比另一个快吗?是否存在其中一个行得通而另一个行不通的情况?

最佳答案

nltk.probability.FreqDistcollections.Counter 的子类。

来自docs :

A frequency distribution for the outcomes of an experiment. A frequency distribution records the number of times each outcome of an experiment has occurred. For example, a frequency distribution could be used to record the frequency of each word type in a document. Formally, a frequency distribution can be defined as a function mapping from each sample to the number of times that sample occurred as an outcome.

The inheritance is explicitly shown from the code从本质上讲,CounterFreqDist 的初始化方式没有区别,请参阅 https://github.com/nltk/nltk/blob/develop/nltk/probability.py#L106

所以在速度方面,创建一个 CounterFreqDist 应该是一样的。速度上的差异应该是微不足道的,但值得注意的是,开销可能是:

  • 在解释器中定义类时编译
  • 鸭子打字的成本.__init__()

主要区别在于 FreqDist 为统计/概率自然语言处理 (NLP) 提供的各种函数,例如finding hapaxes . FreqDist 扩展 Counter 的完整函数列表如下:

>>> from collections import Counter
>>> from nltk import FreqDist
>>> x = FreqDist()
>>> y = Counter()
>>> set(dir(x)).difference(set(dir(y)))
set(['plot', 'hapaxes', '_cumulative_frequencies', 'r_Nr', 'pprint', 'N', 'unicode_repr', 'B', 'tabulate', 'pformat', 'max', 'Nr', 'freq', '__unicode__'])

当谈到使用FreqDist.most_common()时,它实际上是在使用Counter的父函数,所以检索排序的most_common的速度> 两种类型的列表相同。

就个人而言,当我只想检索计数时,我使用 collections.Counter。但是,当我需要进行一些统计操作时,我要么使用 nltk.FreqDist,要么将 Counter 转储到 pandas.DataFrame 中(请参阅Transform a Counter object into a Pandas DataFrame)。

关于python - Python 的 collections.Counter 和 nltk.probability.FreqDist 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603922/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com