查找字符串是否包含 python 列表中的短语

Find if a string contains a phrase from a list in python

我需要查找一个字符串是否包含列表中的一个短语,并打印它。

例如:

my_phrases = ['Hello world', 'apple', 'orange', 'red car']

my_string = 'I am driving a red car'

结果应该是“找到一个短语或单词”并且是“red car”

我找到了一种以非常聪明的方式用单个词来做到这一点的方法(在另一个讨论中找到):

def words_in_string(word_list, my_string):
   return set(word_list).intersection(my_string.split())

所以

if words_in_string(word_list,my_string):
           print('a word has been found ')
for word in words_in_string(word_list,my_string):
           print(word)

如果 word_list 是单个单词的列表,它会起作用,但如果我尝试使用短语,它就不会。

这是否解决了问题:

my_phrases = ['Hello world', 'apple', 'orange', 'red car']

my_string = 'I am driving a red car'


for phrase in my_phrases:
    if phrase in my_string:
        print(phrase)