如何检查数组中的任何字符串是否存在于另一个字符串中?
例如:
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:行得到适当的结果?
如何检查数组中的任何字符串是否存在于另一个字符串中?
例如:
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:行得到适当的结果?
当前回答
如果您想要单词的精确匹配,那么可以考虑对目标字符串进行单词标记。我使用nltk推荐的word_tokenize:
from nltk.tokenize import word_tokenize
下面是接受答案的标记化字符串:
a_string = "A string is more than its parts!"
tokens = word_tokenize(a_string)
tokens
Out[46]: ['A', 'string', 'is', 'more', 'than', 'its', 'parts', '!']
接受的答案修改如下:
matches_1 = ["more", "wholesome", "milk"]
[x in tokens for x in matches_1]
Out[42]: [True, False, False]
在公认的答案中,单词“more”仍然是匹配的。但是,如果“mo”成为匹配字符串,接受的答案仍然找到匹配。这是我不希望看到的行为。
matches_2 = ["mo", "wholesome", "milk"]
[x in a_string for x in matches_1]
Out[43]: [True, False, False]
使用单词标记化,“mo”不再匹配:
[x in tokens for x in matches_2]
Out[44]: [False, False, False]
这是我想要的附加行为。这个答案也回答了这里的重复问题。
其他回答
为了降低复杂度,jbernadas已经提到了aho - corasick -算法。
下面是在Python中使用它的一种方法:
从这里下载aho_corasick.py 将它放在与Python主文件相同的目录中,并将其命名为aho_corasick.py 用以下代码尝试该算法: 导入aho_corasick #(字符串,关键字) Print (aho_corasick(string, ["keyword1", "keyword2"]))
注意,搜索是区分大小写的
在另一个字符串列表中查找多个字符串的一种紧凑方法是使用set.intersection。这比大型集或列表中的列表理解执行得快得多。
>>> astring = ['abc','def','ghi','jkl','mno']
>>> bstring = ['def', 'jkl']
>>> a_set = set(astring) # convert list to set
>>> b_set = set(bstring)
>>> matches = a_set.intersection(b_set)
>>> matches
{'def', 'jkl'}
>>> list(matches) # if you want a list instead of a set
['def', 'jkl']
>>>
为了增加regex的多样性:
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
print 'possible matches thanks to regex'
else:
print 'no matches'
或者如果你的列表太长- any(re.findall(r'|'.join(a), str, re.IGNORECASE))
如果你想要的只是True或False, any()是目前为止最好的方法,但如果你想知道具体匹配哪个字符串/字符串,你可以使用一些东西。
如果你想要第一个匹配(默认为False):
match = next((x for x in a if x in str), False)
如果你想获得所有匹配项(包括重复项):
matches = [x for x in a if x in str]
如果你想获得所有非重复的匹配(不考虑顺序):
matches = {x for x in a if x in str}
如果你想按正确的顺序获得所有非重复的匹配项:
matches = []
for x in a:
if x in str and x not in matches:
matches.append(x)
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')