Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python搜索文本中正则表达式列表的最快方法是什么?_Python_Regex - Fatal编程技术网

使用Python搜索文本中正则表达式列表的最快方法是什么?

使用Python搜索文本中正则表达式列表的最快方法是什么?,python,regex,Python,Regex,假设我有以下列表: l = ['foo', 'bar', 'baz'] 我想知道搜索大文本并返回True文本中是否存在任何字符串的最快方法是什么?使用in关键字,您可以轻松完成以下操作: import re s = 'fgfkgfgujndf foofsdjbnfbarfkdfmdsf' l = ['foo', 'bar', 'baz'] found = re.findall('|'.join(l), s) if found: print found def wordInText(

假设我有以下列表:

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

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

使用
in
关键字,您可以轻松完成以下操作:

import re
s = 'fgfkgfgujndf foofsdjbnfbarfkdfmdsf'

l = ['foo', 'bar', 'baz']
found = re.findall('|'.join(l), s)
if found:
    print found
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

不使用正则表达式。对于简单的字符串来说,这是开销。如果这些字符串确实是您要查找的字符串<代码>s中的“foo”或s中的“bar”或s中的“baz”。如果不是这些,则取决于搜索字符串和目标字符串。你试过什么,速度有多慢,是什么因素导致速度太慢?你如何定义“in”?区分大小写?只有整个单词?@jornsharpe我的意思是不区分大小写的出现。定义“大文本”吗?你想解决的实际问题是什么?
任何
已经短路,如果你去掉
[]
并将列表理解变成一个生成器表达式。@taesu,
是否打印任何(e在文本中表示e在l中)
在找到第一个实例时停止?@paurrx正如jornsharpe指出的那样,它短路了,所以是的。我不知道。好吧,我如何比较执行时间和使用
re
时的执行时间?在大输入集上执行一些操作,但通常情况下,字符串操作比正则表达式操作更可取。
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