我正在將正則運算式串列與字串串列進行匹配。問題是,串列非常大(RegEx 大約 100 萬,字串大約 50T)。我到目前為止是這樣的:
reg_list = ["domain\.com\/picture\.png", "entry{0,9}"]
y = ["test","string","entry4also_found","entry5"]
for r in reg_list:
for x in y:
if re.findall(r, x):
RESULT_LIST.append(x)
print(x)
這在邏輯上非常有效,但對于這些條目數量來說效率低下。有沒有更好(更有效)的解決方案?
提前致謝。
uj5u.com熱心網友回復:
使用any()測驗,如果任何正則運算式匹配,而不是遍歷整個串列。
首先編譯所有的正則運算式,所以這不必重復執行。
reg_list = [re.compile(rx) for rx in reg_list]
for word in y:
if (any(rx.search(word) for rx in reg_list):
RESULT_LIST.append(word)
uj5u.com熱心網友回復:
python -m timeit -s "import re" "re.match('hello', 'hello world')"
100000 loops, best of 3: 3.82 usec per loop
$ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 1.26 usec per loop
因此,如果您打算大量使用相同的正則運算式,那么重新編譯可能是值得的(尤其是對于更復雜的正則運算式)。
uj5u.com熱心網友回復:
想到的唯一改進是
- 在第一次出現時停止匹配以
re.findall嘗試搜索多個匹配項,這不是您所追求的 - 預編譯您的正則運算式。
reg_list = [r"domain\.com/picture\.png", r"entry{0,9}"]
reg_list = [re.compile(x) for x in reg_list] # Step 1
y = ["test","string","entry4also_found","entry5"]
RESULT_LIST = []
for r in reg_list:
for x in y:
if r.search(x): # Step 2
RESULT_LIST.append(x)
print(x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/358674.html
上一篇:使用正則運算式選擇文本的特定部分
