【发布时间】:2019-09-09 00:13:06
【问题描述】:
我正在使用模块 nltk 从大约 210 万个关键字的单词列表中检查好的英语单词。 从文本文件中读取单词,然后检查是否是正确的英文单词,然后将正确的单词写入文本文件。 脚本运行良好,但是速度非常慢,大约每秒 7 次迭代。 有没有更快的方法来做到这一点?
这是我的代码:
import nltk
from nltk.corpus import words
from tqdm import tqdm
total_size = 2170503
with open('two_words.txt','r',encoding='utf-8') as file:
for word in tqdm(file,total=total_size):
word = word.strip()
if all([w in words.words() for w in word.split()]):
with open('good_two.txt', 'a', encoding='utf-8') as file:
file.write(word)
file.write('\n')
else:
pass
有没有更快的方法来做同样的事情? IE 使用 wordnet 或任何其他建议?
【问题讨论】:
-
来自上述链接的建议是 words.words() 一个单词列表,需要 O(n) 时间来检查每个单词。您应该使用一组单词(即 set(words.words()) ,然后花费恒定时间 O(1) 而不是 O(n) 来检查每个单词。
标签: python python-3.x nltk