2012-09-05 49 views
1

我有一个很长的短字符串列表,我想在(通常)很长的文本字符串中搜索所有这些项目。我的列表长度约为500个短字符串,我希望能够使用python查找出现在大约〜10,000个字符的源文本中的所有内容。在python中搜索文本正文中的多个项目的最快方法

这里是我的问题的一个简单的例子:

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"] 

我目前在cleanText发现在searchList出现的项目的方法是:

found = [phrase for phrase in searchList if phrase in cleanText] 

这是在Python的最快方法是什么?它并不是很慢,但在规模上(searchList中有500个项目,其中有一个长度为10,000个字符的cleanText),它看起来比我想要的慢一点。

+0

您的内容是否持续存在?你可以使用全文索引解决方案吗? –

回答

6

你可以尝试一个正则表达式。这可能会加快速度的大名单:

import re 
found = re.findall('|'.join(searchList),cleanText) 

(当然,这个假设没有什么在searchList,将需要进行转义为re的目的。)


正如指出的在评论(感谢anijhaw),你可以通过做退让:

found = re.findall('|'.join(re.escape(x) for x in searchList), cleanText) 

您也可以预编译正则表达式,如果你会使用一次以上的机智h re.compile例如:。

regex = re.compile('|'.join(re.escape(x) for x in searchList)) 
found = regex.findall(cleanText) 

免责声明这些解决方案只能找到非重叠匹配。

+0

你可以使用re.escape作为 – anijhaw

+0

并且编译你的正则表达式,如果你打算不止一次使用它 – anijhaw

+0

@anijhaw - 只要你是re.escape步骤,预编译真的只会节省你在程序中不使用正则表达式,因为''re'缓存了内部的前几个效率。 – mgilson

相关问题