【问题标题】:Check if any element of an array exists in a string (Python)检查字符串中是否存在数组的任何元素(Python)
【发布时间】:2020-11-12 14:19:21
【问题描述】:

注意:我发现了一些类似的问题,但没有专门针对 Python 或此特定场景的问题。


这是一个小示例(工作)sn-p,它在较大的字符串中搜索字符串(从字符串数组中)。

#!/usr/bin/python

matches = [
    "NEEDLE1",
    "NEEDLE2",
    "N33DL3"
]

haystack = 'this is a haystack, there may or may not be a noodley needle around here. Needless to say I hate N33DL3 people'

for match in matches:
    if match in haystack:
        print("Found")

问题:有没有一种“更好”的方法可以做到这一点,而不必遍历 (for match in matches) 每个数组元素?


编辑: 接受的答案有效并且速度很快。以下是时间:

# Ran the following: 

starttime = timeit.default_timer()
for match in matches:
    if match in haystack:
        print("Found with looping in ", timeit.default_timer() - starttime)

starttime = timeit.default_timer()
if any(match in haystack for match in matches):
    print("Found with any() in ", timeit.default_timer() - starttime)

starttime = timeit.default_timer()
if re.search('|'.join(matches), haystack):
    print("Found with regex in ", timeit.default_timer() - starttime)


# After many trial runs, the regex continually came out much (much) faster: 

('Found with looping in ', 9.5367431640625e-07)
('Found with any() in ', 5.0067901611328125e-06)
('Found with regex in ', 0.0003647804260253906)

【问题讨论】:

  • 使用any() 函数。有很多 SO 问题说明了如何做到这一点。
  • any(match in haystack for match in matches)
  • 也可以将matches转为正则表达式,然后检查正则表达式是否匹配。
  • @Barmar 谢谢,我会检查 any() 函数。

标签: python string search


【解决方案1】:

使用re:

import re

matches = ["NEEDLE1", "NEEDLE2", "N33DL3"]
haystack = 'this is a haystack, there may or may not be a noodley needle around here. Needless to say I hate N33DL3 people'

if re.search('|'.join(matches), haystack):
    print("Found")

'|' 符号在正则表达式中表示 or,因此您正在使用此搜索查找 matches 中的任何单词。


编辑

如果您打算经常使用此搜索,我会在全局范围内编译一次正则表达式,或者然后在您需要的任何地方使用编译后的版本,而不是一遍又一遍地创建它:

find_matches = re.compile('|'.join(matches))
#then where you need it:
if find_matches.search(haystack):
    ...

【讨论】:

  • 谢谢我自己从来没有想过这个。我会在接受之前对其进行一些测试,但这看起来又快又便宜,这很好,因为我的“现实世界”应用程序有更大的匹配项和干草堆。
  • 到目前为止,这比我原来的 sn-p 和使用 any(match in haystack for match in matches): 快得多——(快得多,我会根据时间编辑 OP)。
  • 您的原始 sn-p 将在每次找到匹配项时打印 'Found'。如果您想要此结果,请使用re.findallre.finditer 而不是re.search,它将返回所有匹配项的列表/迭代器,而不仅仅是找到任意数量的匹配项
猜你喜欢
  • 1970-01-01
  • 2011-12-23
  • 2013-10-31
  • 2016-09-22
  • 2013-09-27
  • 2022-07-30
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
相关资源
最近更新 更多