nltk.probability.FreqDist 是collections.Counter 的子类。
来自docs:
实验结果的频率分布。一种
频率分布记录每个结果的次数
实验发生了。例如,频率分布可以
用于记录文档中每种单词类型的频率。
形式上,频率分布可以定义为一个函数
从每个样本映射到该样本出现的次数
作为结果。
The inheritance is explicitly shown from the code 本质上,Counter 和 FreqDist 的初始化方式没有区别,请参阅 https://github.com/nltk/nltk/blob/develop/nltk/probability.py#L106
所以速度方面,创建Counter 和FreqDist 应该是相同的。速度上的差异应该是微不足道的,但需要注意的是开销可能是:
- 在解释器中定义类时的编译
- 鸭子打字的成本
.__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)。