我有一个小脚本,希望根据几个条件提取一些独特的单词,并通过检查条件超长。如何实现更快的条件检查功能? python
可能是因为它检查了一个大字典,并且它也将stemmer应用于每个标记。
的条件是:
- 令牌不是在选择的词典
- 令牌长度超过1
- 令牌不是在一组固定的标点符号的
- 令牌不是不是纯数字
- 令牌不以“'s”结尾
有多个条件检查有更快的实现吗?任何基于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
你不会加快条件的多样性;将它们与'和'结合起来是最有用的方法(以防万一它们都需要成立)。但是,您可能会在算法中的其他位置调整结果。你可以使用're.finditer()'而不是'split()'遍历'txt'中的标记;这样你就不会建立你并不需要的所有令牌的列表。 – Alfe
你可以开始把'dictionary'变成一个真正的字典,而不是一个列表。 – user2722968
甚至一套。 '字典= {'苹果','梨','橙',...}' – Alfe