Toptimiz这个词

2024-04-19 07:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

for s_index, s in enumerate(sentences):
        s_tokens = s.split()
        if (local_q_set.intersection(set(s_tokens)) == local_q_set):
            q_results.append(s_index)

上面的代码片段是我用来在包含查询中所有标记的大量文本数据中查找相关句子的核心算法。例如,对于一个查询“happy apple”,它会查找所有句子,其中正好包含一个或多个给定的标记(即“happy”和“apple”)。我的方法很简单:找到公共相交集,看看它们是否匹配。然而,我没有得到足够的表现。如果有人看到了这样的问题优化,我会非常感谢任何方向或链接的想法-谢谢你的时间提前


Tags: in标记appleforindexiflocalsentences
1条回答
网友
1楼 · 发布于 2024-04-19 07:34:24

您可以做一些事情来提高顺序搜索的性能,但真正的提升来自索引标记。你知道吗

设置差异

使用not local_q_set.difference(s_tokens)而不是将交集与原始集进行比较可能会更快一些。你知道吗

正则表达式筛选器

如果你的句子很长,使用正则表达式可能会提供一些速度改进,方法是在检查潜在的标记集之前将它们从句子中分离出来:

import re
tokens     = re.compile("|".join(local_q_set))
tokenCount = len(local_q_set)
for s_index, s in enumerate(sentences):
    s_tokens = tokens.findall(s)
    if len(s_tokens) < tokenCount or local_q_set.difference(s.split()):
       continue
    q_results.append(s_index) 

使用in运算符过滤

您还可以使用一个简单的in操作符来检查是否存在标记,而不是正则表达式(当查询中的标记很少时,这应该会更快):

result = []
tokenSet = set(queryTokens)
for index, sentence in enumerate(sentences):
     if any( token not in sentence for token in queryTokens) \
     or tokenSet.difference(sentence.split()):
         continue
     result.append(index)

缓存句子词集

要改进对同一句子列表进行多个查询时的顺序搜索,可以构建与句子对应的词集缓存。这将消除分析句子的工作,同时通过他们寻找一个匹配。你知道吗

cachedWords = []

queryTokens = ["happy","apple"]

queryTokenSet = set(queryTokens)
if not cachedWords:
    cachedWords = [ set(sentence.split()) for sentence in sentences ]
result = [ index for index,words in enumerate(cachedWords) if not queryTokenSet.difference(words) ]

标记索引

如果要对同一个句子列表执行多个查询,那么在标记和句子索引之间创建映射将更有效。您可以使用字典来实现这一点,然后通过交叉查询的标记的句子索引直接获得查询结果:

tokenIndexes = dict()
for index,sentence in enumerate(sentences):
    for token in sentence.lower().split():
        tokenIndexes.setdefault(token,[]).append(index)

def tokenSet(token): return set(tokenIndexes.get(token,[]))

queryTokens = ["happy","apple"]

from functools import reduce
result = reduce(set.intersection , (tokenSet(token) for token in queryTokens) )

这将允许您使用set运算符经济地实现复杂查询。例如:

import re

querySring = " happy & ( apple | orange | banana ) "
result = eval(re.sub("(\w+)",r"tokenSet('\1')", querySring)) 

# re.sub(...) transforms the query string into " tokenSet('happy') & ( tokenSet('apple') | tokenSet('orange') | tokenSet('banana') ) "

性能测试:

我做了一些性能测试(在80000个句子中的一个句子中找到两个标记):

original algorithm: 105 ms           1x
set.difference:      88 ms         1.2x
regular expression:  60 ms         1.8x
"in" operator:       43 ms         2.4x
caching word sets:   23 ms         4.6x (excluding 187ms to build cache)
token indexing:       0.0075 ms  14000x (excluding 238ms to build tokenIndexes)

因此,如果要对同一个句子执行多个查询,使用tokenindexing,那么一旦构建了tokenIndexes字典,响应速度将提高1.4万倍。

相关问题 更多 >