Faster way to remove stop words in Python

前端 未结 4 724
情歌与酒
情歌与酒 2020-12-04 09:34

I am trying to remove stopwords from a string of text:

from nltk.corpus import stopwords
text = \'hello bye the the hi\'
text = \' \'.join([word for word in          


        
4条回答
  •  天涯浪人
    2020-12-04 09:52

    Try caching the stopwords object, as shown below. Constructing this each time you call the function seems to be the bottleneck.

        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()
    

    I ran this through the profiler: python -m cProfile -s cumulative test.py. The relevant lines are posted below.

    nCalls Cumulative Time

    10000 7.723 words.py:7(testFuncOld)

    10000 0.140 words.py:11(testFuncNew)

    So, caching the stopwords instance gives a ~70x speedup.

提交回复
热议问题