我正在尝试从文本字符串中删除停用词:
from nltk.corpus import stopwords
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in (stopwords.words('english'))])
我正在处理 600 万个这样的字符串,因此速度很重要。分析我的代码,最慢的部分是上面的行,有更好的方法吗?我正在考虑使用类似正则表达式的东西re.sub
但我不知道如何编写一组单词的模式。有人可以帮我吗,我也很高兴听到其他可能更快的方法。
注意:我尝试了某人的包装建议stopwords.words('english')
with set()
但这没有什么区别。
谢谢。
尝试缓存停用词对象,如下所示。每次调用函数时都构建这个似乎是瓶颈。
from nltk.corpus import stopwords
cachedStopWords = stopwords.words("english")
def testFuncOld():
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in stopwords.words("english")])
def testFuncNew():
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in cachedStopWords])
if __name__ == "__main__":
for i in xrange(10000):
testFuncOld()
testFuncNew()
我通过分析器运行了这个:python -m cProfile -s 累积测试.py。相关行发布在下面。
nCalls 累计时间
10000 7.723 个单词.py:7(testFuncOld)
10000 0.140 个单词.py:11(testFuncNew)
因此,缓存停用词实例可提供约 70 倍的加速。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)