Python 检查另一个字符串中是否存在多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3389574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:47:57  来源:igfitidea点击:

Check if multiple strings exist in another string

pythonarraysstringexists

提问by jahmax

How can I check if any of the strings in an array exists in another string?

如何检查数组中的任何字符串是否存在于另一个字符串中?

Like:

喜欢:

a = ['a', 'b', 'c']
str = "a123"
if a in str:
  print "some of the strings found in str"
else:
  print "no strings found in str"

That code doesn't work, it's just to show what I want to achieve.

该代码不起作用,只是为了显示我想要实现的目标。

采纳答案by Mark Byers

You can use any:

您可以使用any

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

Similarly to check if allthe strings from the list are found, use allinstead of any.

与检查是否找到列表中的所有字符串类似,请使用all代替any

回答by Seamus Campbell

You need to iterate on the elements of a.

您需要迭代 a 的元素。

a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:    
    if item in str:
        found_a_string = True

if found_a_string:
    print "found a match"
else:
    print "no match found"

回答by mluebke

a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"

回答by jbernadas

You should be careful if the strings in aor strgets longer. The straightforward solutions take O(S*(A^2)), where Sis the length of strand A is the sum of the lenghts of all strings in a. For a faster solution, look at Aho-Corasickalgorithm for string matching, which runs in linear time O(S+A).

如果字符串变长astr变长,您应该小心。简单的解决方案采用 O(S*(A^2)),其中S是 的长度,strA 是 中所有字符串的长度之和a。要获得更快的解决方案,请查看用于字符串匹配的Aho-Corasick算法,该算法在线性时间 O(S+A) 内运行。

回答by Shankar ARUL - jupyterdata.com

Just to add some diversity with regex:

只是为了增加一些多样性regex

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

or if your list is too long - any(re.findall(r'|'.join(a), str, re.IGNORECASE))

或者如果你的清单太长—— any(re.findall(r'|'.join(a), str, re.IGNORECASE))

回答by zondo

any()is by far the best approach if all you want is Trueor False, but if you want to know specifically which string/strings match, you can use a couple things.

any()如果您想要的只是Trueor False,这是迄今为止最好的方法,但是如果您想具体知道哪个字符串/字符串匹配,您可以使用一些东西。

If you want the first match (with Falseas a default):

如果你想要第一场比赛(False默认情况下):

match = next((x for x in a if x in str), False)

If you want to get all matches (including duplicates):

如果要获取所有匹配项(包括重复项):

matches = [x for x in a if x in str]

If you want to get all non-duplicate matches (disregarding order):

如果您想获得所有非重复匹配项(不考虑顺序):

matches = {x for x in a if x in str}

If you want to get all non-duplicate matches in the right order:

如果您想以正确的顺序获取所有非重复匹配项:

matches = []
for x in a:
    if x in str and x not in matches:
        matches.append(x)

回答by Trinadh Koya

It depends on the context suppose if you want to check single literal like(any single word a,e,w,..etc) inis enough

这取决于上下文猜,如果你要检查,如单文字(任何一个字,E,W,..等)足够

original_word ="hackerearcth"
for 'h' in original_word:
      print("YES")

if you want to check any of the character among the original_word: make use of

如果要检查 original_word 中的任何字符:请使用

if any(your_required in yourinput for your_required in original_word ):

if you want all the input you want in that original_word,make use of all simple

如果你想在那个 original_word 中输入你想要的所有输入,请使用 all simple

original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
    print("yes")

回答by Domi W

jbernadas already mentioned the Aho-Corasick-Algorithmin order to reduce complexity.

jbernadas 已经提到了Aho-Corasick-Algorithm以降低复杂性。

Here is one way to use it in Python:

这是在 Python 中使用它的一种方法:

  1. Download aho_corasick.py from here

  2. Put it in the same directory as your main Python file and name it aho_corasick.py

  3. Try the alrorithm with the following code:

    from aho_corasick import aho_corasick #(string, keywords)
    
    print(aho_corasick(string, ["keyword1", "keyword2"]))
    
  1. 这里下载 aho_corasick.py

  2. 将它放在与主 Python 文件相同的目录中并命名 aho_corasick.py

  3. 使用以下代码尝试算法:

    from aho_corasick import aho_corasick #(string, keywords)
    
    print(aho_corasick(string, ["keyword1", "keyword2"]))
    

Note that the search is case-sensitive

注意搜索区分大小写

回答by LeftSpace

flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')

output example image

输出示例图像

回答by Ivan Mikhailov

I would use this kind of function for speed:

我会使用这种功能来提高速度:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False