使用Python搜索文本中regex列表的最快方法是什么?

2024-04-19 12:59:02 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下列表:

l = ['foo', 'bar', 'baz']

我想知道搜索大文本并返回True(如果文本中存在任何字符串)的最快方法是什么?你知道吗


Tags: 方法字符串文本true列表foobarbaz
3条回答
text = 'slfdk gaklsdjfl asdkfljasdkljf qkwlejlqwekj bazaklajsdfkj gsadf'
l = ['foo', 'bar', 'baz']

print any(e in text for e in l)
import re
s = 'fgfkgfgujndf foofsdjbnfbarfkdfmdsf'

l = ['foo', 'bar', 'baz']
found = re.findall('|'.join(l), s)
if found:
    print found

使用in关键字,您可以轻松地执行以下操作:

def wordInText(list, text):
  for word in list:
    if word in text: return True
  return False

wordInText(['test', 'cat', 'exam'], 'this is a simple example') # returns True
wordInText(['test', 'cat', 'max'], 'this is a simple example') # returns False

相关问题 更多 >