簡體   English   中英

搜索元組列表以查找匹配的 substring 的算法方法?

[英]Algorithmic way to search a list of tuples for a matching substring?

我有一個元組列表,大約有 100k 個條目。 每個元組由一個 id 和一個字符串組成,我的目標是列出元組的 id,其字符串包含給定子字符串列表中的 substring。 我目前的解決方案是通過集合理解,ids 可以重復。

tuples = [(id1, 'cheese trees'), (id2, 'freezy breeze'),...]
vals = ['cheese', 'flees']
ids = {i[0] for i in tuples if any(val in i[1] for val in vals)}

output: {id1}

有沒有一種算法可以更快地做到這一點? 我對精確的 substring 匹配感興趣,也可能對近似匹配感興趣。 我在這里追求的主要是一種算法,它比理解提供速度優勢。

免責聲明我是trrex的作者

對於完全匹配的情況,解決此問題的一種方法是使用Trie ,如評論中所述。 trrex是一個制作 Trie-Regex(正則表達式格式的 Trie)的庫,可以與 Python 的正則表達式引擎一起使用:

import random
import pandas as pd
import trrex as tx
import re

df = pd.read_csv('jeopardy-small.csv')
with open('words-sample') as infile:
    words = [line.strip() for line in infile]


tuples = [(random.randint(1, 250), sentence) for sentence in df['question']]


def fun_kislyuk(ws, ts):
    return {t[0] for t in ts if any(w in t[1] for w in ws)}


def fun_trrex(ws, ts):
    pattern = re.compile(tx.make(ws, left='', right=''))
    return {i for i, s in ts if pattern.search(s)}


if __name__ == "__main__":
    print(fun_trrex(words, tuples) == fun_kislyuk(words, tuples))

Output

True

上述功能的時間安排是:

%timeit fun_trrex(words, tuples)
11.3 ms ± 34.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit fun_kislyuk(words, tuples)
67.5 ms ± 1.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

數據是來自 jeopardy 的大約 2000 個問題和 500 個隨機選擇的單詞的列表。 你可以在這里找到重現實驗的資源。

更新

如果添加評論中提到的分組策略,時間改進會增加,下面是 function:

def fun_grouping_trrex(ws, ts):
    pattern = re.compile(tx.make(ws, left='', right=''))
    groups = defaultdict(list)
    for i, s in ts:
        groups[i].append(s)

    return {i for i, vs in groups.items() if any(pattern.search(v) for v in vs)}

和時間:

%timeit fun_trrex(words, tuples)
11.2 ms ± 61.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit fun_grouping_trrex(words, tuples)
4.96 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit fun_kislyuk(words, tuples)
67.4 ms ± 1.47 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

分組+ trrex的方法使您的性能提高了大約10 倍 但是對最后一個結果持保留態度,因為它非常依賴於數據集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM