python中最快的方式来搜索文本正文中的多个项目

use*_*440 1 python search list

我有一长串短字符串,我想在(通常)长文本字符串中搜索所有这些项目.我的列表有~500个短字符串的长度,我想找到所有在源文本中出现的大约使用python约10,000个字符.

这是我的问题的一个简短示例:

cleanText = "four score and seven years ago our fathers brought forth on this continent a new nation conceived in Liberty and dedicated to the proposition that all men are created equal"
searchList = ["years ago","dedicated to","civil war","brought forth"]
Run Code Online (Sandbox Code Playgroud)

我目前在cleanText中查找searchList中的项目的方法是:

found = [phrase for phrase in searchList if phrase in cleanText]
Run Code Online (Sandbox Code Playgroud)

这是python中最快的方式吗?它并不是很慢,但是在规模上(在searchList中有500个项目,一个长度为10,000个字符的cleanText)它似乎比我想要的慢一点.

mgi*_*son 5

你可以试试正则表达式.这可能会加快大型列表的速度:

import re
found = re.findall('|'.join(searchList),cleanText)
Run Code Online (Sandbox Code Playgroud)

(当然,这假设没有任何searchList内容需要为了目的而被转义re.)


正如评论中指出的那样(感谢anijhaw),您可以通过以下方式进行转义:

found = re.findall('|'.join(re.escape(x) for x in searchList), cleanText)
Run Code Online (Sandbox Code Playgroud)

您还可以预编译正则表达式,如果您将多次使用它,re.compile例如:

regex = re.compile('|'.join(re.escape(x) for x in searchList))
found = regex.findall(cleanText)
Run Code Online (Sandbox Code Playgroud)

免责声明这些解决方案仅发现非重叠匹配.