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

例如:

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]

这是我想要的附加行为。这个答案也回答了这里的重复问题。

其他回答

这取决于上下文 假设你想检查单个文字(任何单个单词a,e,w,..等)就足够了

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

如果你想检查original_word中的任何一个字符: 利用

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

如果您想要original_word中的所有输入,请使用所有输入 简单的

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

这是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")
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']


# for each
for field in mandatory_fields:
    if field not in data:
        print("Error, missing req field {0}".format(field));

# still fine, multiple if statements
if ('firstName' not in data or 
    'lastName' not in data or
    'age' not in data):
    print("Error, missing a req field");

# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
    print("Error, missing fields {0}".format(", ".join(missing_fields)));

一个惊人的快速方法是使用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'。

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