Python 如何从单词列表中找到它在字符串中找到的单词

Python 如何从单词列表中找到它在字符串中找到的单词,python,regex,Python,Regex,用这个我们怎么知道哪个词是现在的 word_list = ['hello','hi','super'] if any(word in string for word in word_list): print('found') 通过这个,我可以遍历这些行,但无法找到它在那行中找到的单词 例如: 在输入中考虑4行 Hello samuel\n Hi how are you\n I’m super\n Thanks 预期产出: Hello,true Hi,true Super,true

用这个我们怎么知道哪个词是现在的

word_list = ['hello','hi','super']
if any(word in string for word in word_list):
    print('found')  
通过这个,我可以遍历这些行,但无法找到它在那行中找到的单词

例如: 在输入

中考虑4行
Hello samuel\n
Hi how are you\n
I’m super\n
Thanks
预期产出:

Hello,true
Hi,true
Super,true
N/a,false
但是有人能告诉我如何打印它在其中找到的单词吗。

这里有一种方法:

Word_list=['hello','hi','super']

l = ["Hello samuel","Hi how are you","I’super","Thankq"]

for i in l:
    k = [x for x in i.split(' ') if x.lower() in Word_list]
    if k:
        print(f'{k[0]}, true')
    else:
        print(f'N/A, false')

Hello, true
Hi, true
N/A, false
N/A, false

您可以这样做:

str = """Hello samuel
Hi how are you
hi I’super
Thankq"""


word_list=["hello","hi","super"]

for line in str.split("\n"):
    word_found = [word.lower() in line.lower() for word in word_list]
    word_filtered = [i for (i, v) in zip(word_list, word_found) if v]
    print("{},{}".format(" ".join(word_filtered) if word_filtered else "n/a", not not word_filtered))
基本上,您的word列表中的word所做的是创建一个列表,具体取决于您当前正在处理的行
any
仅检查列表中的任何元素是否为
True
并返回True

有了这些知识,我们可以构建这样的东西

word\u found=[word.lower()在line.lower()用于word\u列表中的word]
如果该行包含此位置的单词,则生成带有
True
的布尔列表,否则为
False
。正如您所看到的,I user lower()不区分大小写。如果这不是您想要的,请更改。但是从你的输出来看,这就是你想要的

word\u filtered=[i for(i,v)in zip(word\u list,word\u found)if v]
使用此选项,我过滤掉行中不存在的所有单词

print(“{},{}”.format(“.join(word\u filtered)if word\u filtered else“n/a”,not word\u filtered))
这是为了创建预期的输出

输出:
如您所见,我稍微修改了您的输入(参见第3行)。正如您所看到的,即使一行中有多个匹配项,此解决方案也会打印任何单词

你在乎单词是否不区分大小写吗?
hello,True
hi,True
hi super,True
n/a,False