我有一個串列,其中包含大約。10.000 個字串,我想使用正則運算式模式在此串列中檢測到這一點。當我使用 re.compile 時,只應用一種正則運算式模式需要很長時間。Python有什么辦法讓它更快嗎?
這是我的代碼:
import re
list_of_strings = ["I like to eat meat", "I don't like to eat meat", "I like to eat fish", "I don't like to eat fish"]
outcome = [x for x in list_of_strings if len(re.compile(r"I like to eat (.*?)").findall(x)) != 0]
Out[6]: ['I like to eat meat', 'I like to eat fish']
這里我只有 4 個字串來演示這個案例。實際上,代碼應該處理 10.000 個字串。
我也可以使用多重處理來解決這個問題,但也許還有另一種解決方案,其中存在 pytorch、pyspark 或其他框架。
[編輯]感謝所有答案。我應該提到每個字串都是一篇文章。因此,從正則運算式處理的不僅僅是一句話。
我還想說這里的正則運算式不是那個問題。所以這不是要討論的話題。
uj5u.com熱心網友回復:
re.compile設計為只能使用一次。編譯一次,然后使用更有效的編譯正則運算式。
import re
pattern = re.compile(r"I like to eat (.*?)")
list_of_strings = ["I like to eat meat", "I don't like to eat meat", "I like to eat fish", "I don't like to eat fish"]
outcome = [x for x in list_of_strings if pattern.match(x)]
您的示例很好地說明了 的使用re.compile(),即當您大量使用正則運算式時。
uj5u.com熱心網友回復:
您也可以考慮回圈串列。
new_list = []
for item in list_of_strings:
if 'I like to eat' in item:
new_list.append(item)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530879.html
上一篇:根據存盤在串列中的列名和值從data.frame中選擇條目
下一篇:使用串列作為條件洗掉字典的專案
