我有一个来宾名称列表,称为“名称列表”。 而且,我有一个已转换为列表“句子”的字符串。 那么,如何检查“句子”中“客人名单”中是否有客人的名字之一?
import re
namelist = ['Nana','Bebe','Kuku','Bumbum']
textinSTR = ('I have invited Kuku, let him in')
sentence = re.sub("[^\w]", " ", textinSTR).split()
# I tried this
if namelist in sentence :
print('bingo')
else :
print('no bingo')
#kuku is in the namelist, but no bingo :(
答案 0 :(得分:0)
Python提供成员资格检查。因此,您可以遍历nameList
中的项目,并检查sentence
中是否存在该项目。此成员资格检查使您可以找到完美的匹配。另外,如果名称以小写字母开头,您应该执行不区分大小写的检查。使用lower()
可以小写列表和句子中的字符串。
namelist = ['Nana','Bebe','Kuku','Bumbum', 'sarah']
sentence = ('I have invited Kuku and Sarah, let him in')
for i in namelist:
if i.lower() in sentence.lower():
print('Bingo! Found {} in sentence'.format(i))
else :
print('no bingo')
#Output:
no bingo
no bingo
Bingo! Found Kuku in sentence
no bingo
Bingo! Found sarah in sentence