我一直在玩不同的方式(在Python 2.7中)从语料库或字符串列表中提取(单词,频率)元组列表,并比较它们的效率.据我所知,在正常情况下列表未排序的情况下,模块中的Counter方法collections优于我在其他地方提出或找到的任何方法,但它似乎没有太大的好处.预先排序的列表,我已经提出了在这种特殊情况下轻松击败它的方法.那么,简而言之,是否有任何内置的方法来告知Counter列表已经排序以进一步加快它的速度?
(下一部分是未分类的列表,其中Counter工作魔法;你可能想要在处理排序列表时跳到它失去魅力的那一端.)
天真的方法是使用sorted([(word, corpus.count(word)) for word in set(corpus)]),但一个可靠的,只要你的语料库是几千个条目你进入运行时的问题-这并不奇怪,因为你通过的n个字的完整列表运行男也曾多次,其中m为唯一单词的数量.
因此,我试图做之前,而不是我发现的Counter是确保所有的搜索都是严格的地方,首先分拣输入表(我也有删除的数字和标点符号和所有条目转换为小写,以避免像"富"重复, 'Foo'和'foo:').
#Natural Language Toolkit, for access to corpus; any other source for a long text will do, though.
import nltk
# nltk corpora come as a class of their own, as I udnerstand it presenting to the
# outside as a unique list but underlyingly represented as several lists, with no more
# than one ever …Run Code Online (Sandbox Code Playgroud)