【问题标题】:Is there any faster way to check from a words-list with nltk with python?有没有更快的方法从带有 python 的 nltk 的单词列表中检查?
【发布时间】: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


【解决方案1】:

您可以通过将 words.words() 转换为一组来加快速度,如下面的测试所示。

from nltk.corpus import words
import time
# Test Text
text = "she sell sea shell by the seashore"

# Original Method
start = time.time()
x = all([w in words.words() for w in "she sell sea shell by the seashore".split()])
print("Duration Original Method: ", time.time() - start)

# Time to convert words to set
start = time.time()
set_words = set(words.words())
print("Time to generate set: ", time.time() - start)

# Test Using Set (Singe iteration)
start = time.time()
x = all([w in set_words for w in "she sell sea shell by the seashore".split()])
print("Set using 1 iteration: ", time.time() - start)

# Test Using Set (10, 000 iterations)
start = time.time()
for k in range(100000):
    x = all([w in set_words for w in "she sell sea shell by the seashore".split()])
print("Set using 100, 000 iterations: ", time.time() - start)

结果显示使用 set ~200,000 更快。 这与 words.words() 有 236, 736 个元素有关,因此 n ~ 236, 736 但是,我们通过使用集合将每次查找的时间从 O(n) 减少到 O(1)

Duration Original Method:  0.601 seconds
Time to generate set:  0.131 seconds
Set using 1 iteration:  0.0 seconds
Set using 100, 000 iterations:  0.304 seconds

【讨论】:

    【解决方案2】:
    1. 我会尝试使用线程。因为您只在一个线程上执行此算法。但请注意,因为一个文件的多个可写流可能会出现问题。获得所需的所有单词后,只需合并这些文件即可。
    2. 问题是python很慢。如果您需要更快的解决方案,我会考虑更改解释器不执行的语言(当然,不错的选择是示例 C/C++),或者您可以从 python 中用另一种语言执行这段代码,然后继续使用 python。
    3. 如果您不需要 .txt 输出文件,将数据写入二进制文件可能会更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多