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

例如:

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

我如何替换如果a在s:行得到适当的结果?


当前回答

一个惊人的快速方法是使用set:

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

如果a不包含任何多字符值(在这种情况下使用上面列出的any),则此方法有效。如果是这样,将a指定为字符串会更简单:a = 'abc'。

其他回答

这是set的另一个解。使用set.intersection。对于一行代码。

subset = {"some" ,"words"} 
text = "some words to be searched here"
if len(subset & set(text.split())) == len(subset):
   print("All values present in text")

if subset & set(text.split()):
   print("Atleast one values present in text")

你可以使用任何:

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

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

类似地,要检查是否找到列表中的所有字符串,请使用all而不是any。

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')

为了降低复杂度,jbernadas已经提到了aho - corasick -算法。

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

从这里下载aho_corasick.py 将它放在与Python主文件相同的目录中,并将其命名为aho_corasick.py 用以下代码尝试该算法: 导入aho_corasick #(字符串,关键字) Print (aho_corasick(string, ["keyword1", "keyword2"]))

注意,搜索是区分大小写的

python文档中推荐的regex模块支持这一点

words = {'he', 'or', 'low'}
p = regex.compile(r"\L<name>", name=words)
m = p.findall('helloworld')
print(m)

输出:

['he', 'low', 'or']

实现的一些细节:link