检查 Python 输入是否包含关键字列表

Check if Python input contains a list of keywords

也就是这个的正确版本:

if ['hi', 'hello', 'greetings'] in userMessage:
    print('Hello!')

我试过上面显示的内容,但它说它不能使用列表,它必须使用单个字符串。如果我将数组设置为 object/variable,也是一样的。如果我使用 "or" 它似乎并不完全有效。

你可以这样做:

found = set(['hi','hello','greetings']) & set(userMessage.split())
for obj in found:
    print found

如果您也在寻找多个单词

如果目标只是说明是否有任何已知列表出现在 userMessage 中,而您不关心它是哪一个,use any with a generator expression:

if any(srchstr in userMessage for srchstr in ('hi', 'hello', 'greetings')):

它会在命中时short-circuit,所以如果输入中出现hi,它不会检查其余部分,并立即returns True .

如果单词必须作为单独的单词来查找(所以 userMessage = "This" 应该是假的,即使 hi 出现在其中),那么使用:

if not {'hi', 'hello', 'greetings'}.isdisjoint(userMessage.split()):

也是 short-circuit,但方式不同;它迭代 userMessage.split() 直到匹配其中一个关键字,然后停止并 returns Falsenot 翻转为 True),返回 True(由 not 翻转为 False)仅当 none 个单词与关键字匹配时。

您还可以使用 Set 比较多个元素:

if set(['hi', 'hello', 'greetings']) <= set(userMessage.split()):
   print("Hello!")

但要小心使用split(),一旦它会避免标点符号。因此,如果您的 userMessage 类似于 "hi, hello, greetings.",它会将这些词与 ["hi,"、"hello,"、"greetings."]

进行比较