如何实现更快的状态检查功能?蟒

How to implement a faster condition checking function? python

本文关键字:状态 检查 功能 何实现 实现      更新时间:2023-10-16

我有一个小脚本,它想根据几个条件提取一些独特的单词,检查条件需要很长时间。

可能是因为它检查了一个大型字典,并且它还对每个令牌应用了一个词干分析器。

条件是:

  • 令牌不在所选字典中
  • 令牌长度大于 1
  • 标记不在一组固定的标点符号中
  • 令牌不是纯数字
  • 令牌不以"的"
  • 结尾

是否有更快的多条件检查实施?任何基于 python 的解决方案都是可以接受的,即使使用子进程或 cython 或调用 c/c++ 实现。

请记住,实际上,有更多的条件,字典最多有 100,000 个条目。我已经做了如下的事情,即使有yield,链接多个条件也很慢。

import string
from nltk.stem import PorterStemmer
porter = PorterStemmer()
dictionary = ['apple', 'pear', 'orange', 'water', 'eat', 'the', 'with', 'an', 'pie', 'full', 'of', 'water', 'at', 'lake', 'on', 'wednesday', 'plus', 'and', 'many', 'more', 'word']
text = "PEAR eats the Orange, with an Apple's MX2000 full of water - h20 - at Lake 0129 on wednesday."
def extract(txt, dic):
    for i in txt.split():
        _i = i.strip().strip(string.punctuation).lower()
        if _i not in dic and len(_i) > 1 and not _i.isdigit() 
        and porter.stem(_i) not in dictionary and not i.endswith("'s"): 
            yield _i
for i in extract(text, dictionary):
    print i

[出]

MX2000
h20

我脑海中浮现的两件事:

  1. 将字典更改为set(如@Alfe建议的那样)。考虑到数据的长度很长,这肯定会有助于提高速度。
  2. 由于一旦某些规则为假,比较就会结束,因此您可以重新排列测试,以便首先运行最快和/或最具歧视性的规则。不过,在这种情况下,我并不直接清楚最好的顺序。尝试一下。