[英]Fastest way of checking for word in huge list of keywords - Python performance
感谢您惊人的快速反应。 Stackoverflow太棒了!
我需要检查一个单词(或者更确切地说是数千个)是否与包含关键字的dict相匹配。
例如,假设我有一个字符串: "The fluffy fox jumped the friggin fence."
我需要根据关键字的字符检查字符串的每个单词,如果匹配,则返回所有值。
我创建了一个dict filters
:( uniqueid
表示ie。“lk2m3lk4m2”,rest是'static'。)
filters:
{ "fox" : [
{ 'subscription' : 'uniqueid', 'link' : 'uniqueid' },
{ 'subscription' : 'uniqueid', 'link' : 'uniqueid' }
]},
{ "fence" : [
{ 'subscription' : 'uniqueid', 'link' : 'uniqueid' }
]}
...并计划迭代字符串中每个单词的过滤器(我必须以大约5000字/秒的速度执行此操作。换句话说,性能是问题所有。
过滤关键字的数量可能会增加到数千,而字符串永远不会超过正常的句子长(即5-20个字)。 因此,我将迭代字符串中的每个单词,并检查它是否包含在filter-list中。 然而,在500句/秒,我仍然在看很多计算。
例如,是否可以对列表进行排序(即列表中的dict键),从而大幅提高性能? 是否有我应该使用的C实现(就像我使用cjson具有很好的性能提升)?
对不起有点流动的问题 - 但我应该怎么做这个任务?
编辑:
预期投入:
"The fluffy fox jumped the friggin fence."
预期产量:
{ 'subscription' : 'flskdmfslk32232', 'link' : 'sfdksmfls22323' }, { 'subscription' : '3023940fsdf', 'link' : 'sdflsfm223' }
(即每个匹配关键字下列出的订阅。)
您可以通过执行filters.has_key(word)或执行以下操作来确定单词是否是过滤器中的键。
subscriptions = filters.get(word)
if subscriptions is not None:
pass # TODO do something with subscriptions
要么:
try:
subscriptions = filters[word]
# TODO do something with subscriptions
except:
pass # probably don't need to do anything if not present
没有必要迭代过滤器中的每个条目。 相反,您需要拆分输入字符串,将每个单词添加到Set(以消除重复项),然后迭代您的集合以查找过滤器字典中的每个单词。
在Python中执行此操作的最快方法是使用字典查看其中的每个单词,并累积和关联值。 主要数据结构可能如下所示:
filters = {
"fox" : (
('uniqueid1', 'uniqueid2'),
('uniqueid3', 'uniqueid4'),
),
"fence" : (
('uniqueid5', 'uniqueid6'),
),
}
使用这种方式(在8位字符上):
from string import punctuation
sentence = 'The fluffy fox jumped the friggin fence.'
sentence = sentence.translate(None, punctuation) # remove punctuation chars
print [filters.get(word) for word in sentence.split() if word in filters]
或者它可能更快(找出时间)这样可以避免双字典查找:
from string import punctuation
def map_words(sentence):
for word in sentence.translate(None, punctuation).split():
try:
yield filters[word]
except KeyError:
pass
sentence = 'The fluffy fox jumped the friggin fence.'
print [v for v in map_words(sentence)]
无论哪种方式,这是输出:
[(('uniqueid1', 'uniqueid2'), ('uniqueid3', 'uniqueid4')), (('uniqueid5', 'uniqueid6'),)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.