【问题标题】:Check if multiple strings are in another string检查多个字符串是否在另一个字符串中
【发布时间】:2019-07-05 19:39:01
【问题描述】:

我正在制作一个聊天机器人,它会查找特定术语以做出相关响应,但我正在努力寻找一种从字符串中查找关键词的方法。

我已经尝试过使用word.find()word in str,但我可能在其中的某个地方遇到了问题。

while True:
    user = input("what's up?")
    if "sad" or "unhappy" or "depressed" in user:
        print("oh that's quite sad")
    else:
        print("that's good")

无论我输入什么,它都会不断地返回“哦,这很可悲”。

【问题讨论】:

标签: python-3.x loops


【解决方案1】:

解决方案 1:

while True:
    user = input("what's up?")
    if "sad" in user or "unhappy" in user or "depressed" in user:
        print("oh that's quite sad")
    else:
        print("that's good")

解决方案 2:使用any

预先定义字符串并使用它:

mylist = ["sad","unhappy","depressed"]
while True:
    user = input("what's up?")
    if any([x in user for x in mylist]):
        print("oh that's quite sad")
    else:
        print("that's good")

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 2019-05-11
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2011-02-07
    相关资源
    最近更新 更多