我正在努力消除所有非英语单词从许多(10万)预印本文本文件(波特词干和小写,删除所有非a-z字符)。我已经将这个过程并行化以加快速度,但它仍然非常缓慢。在python中有没有更有效的方法?你知道吗
englishwords = list(set(nltk.corpus.words.words()))
englishwords = [x.lower() for x in list(englishwords)]
englishwords = [ps.stem(w) for w in englishwords]
# this step takes too long:
shareholderletter= ' '.join(w for w in nltk.wordpunct_tokenize(shareholderletter) if w in englishwords)
您正在检查
somthing in otherthing
-并且您的otherthing
是一个列表。你知道吗列表很适合存储内容,但是查找“does x is in”需要
O(n)
。你知道吗使用
set
代替,它将查找放在O(1)
和中,它将删除所有重复项,因此如果您有重复项,您的基本大小也将放在一起查找。你知道吗如果你的集合之后没有改变,那么就使用一个
frozenset
-它是不可变的。你知道吗读取:Documentation of sets
如果使用@DeepSpace的建议,并利用set操作,您将获得更好的性能:
输出:
见set operations
O(n):最糟糕的情况:你的单词是你列表中20万个单词中的最后一个,你检查整个列表-这需要20万个检查。你知道吗
O(1):查找时间是恒定的,无论数据结构中有多少项,都需要相同的时间来检查其是否存在。为了获得这个好处,
set
有一个更复杂的存储解决方案,它需要稍多的内存(然后是一个列表)才能在查找时执行得如此出色。你知道吗编辑:不在集合/列表中查找单词的最坏情况:
相关问题 更多 >
编程相关推荐