尝试缓存停用词对象,如下所示。每次调用函数时都要构造它,这似乎是瓶颈。
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()
:我通过探查跑这 。相关行如下。
nCalls累积时间
10000 7.723个单词.py:7(testFuncOld)
10000 0.140个单词。py:11(testFuncNew)
因此,缓存停用词实例可以使速度提高约70倍。