【发布时间】:2014-03-19 22:30:59
【问题描述】:
哪个 ngram 实现在 python 中最快?
我尝试分析 nltk 与 scott 的 zip (http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/):
from nltk.util import ngrams as nltkngram
import this, time
def zipngram(text,n=2):
return zip(*[text.split()[i:] for i in range(n)])
text = this.s
start = time.time()
nltkngram(text.split(), n=2)
print time.time() - start
start = time.time()
zipngram(text, n=2)
print time.time() - start
[出]
0.000213146209717
6.50882720947e-05
在 python 中生成 ngram 有更快的实现吗?
【问题讨论】:
-
您可以为
n的不同值设置单独的函数吗?在zipngram中对其进行硬编码并删除列表表达式在一些粗略的实验中提供了 1.5-2 倍的加速。 -
当然,任何方法,只要它更快并且达到相同的输出 =)。愿意分享代码和一些分析吗?
-
在 Cython 或 C 中通过
cffi实现是否算数?如果字母表是 unicode 而不是 ACSII,那么这些将是最快的,尽管不是微不足道的。如果是后者,SSE 大会可能会大打出手。此外,如果文本足够长,您可能希望将工作分散到各个核心。 -
当然,只要能从python调用脚本,越快越好。
-
如果你已经使用 spacy 并且你的文本已经被转换成 spacy
doc,你可以试试 textacy 的 ngram 实现:chartbeat-labs.github.io/textacy/getting_started/…
标签: python nlp nltk information-retrieval n-gram