python-3.x - 检查多个字符串是否在另一个字符串中
问题描述
我正在制作一个聊天机器人,它会查找特定术语以做出相关响应,但我正在努力寻找一种从字符串中查找关键词的方法。
我已经尝试过使用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")
无论我输入什么,它都会不断返回“哦,这很可悲”。
解决方案
解决方案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")
推荐阅读
- pandas - Pandas Dictionary:如何通过将输入值与分配给单个键的多个值匹配来返回键
- javascript - 使用 Ajax 的按钮在 Django 项目中不起作用
- tensorflow - 如何将 TensorFlow 模型部署到云端?
- powershell - 比较两个列表并用powershell做一个报告
- r - 在 R 中循环读取多个 .tsv 文件
- excel - Excel:匹配两列返回值在查找列表和表数组中有重复值
- c# - RestSharp在重定向后获取url
- javascript - 酒树拖放 - 如何防止从拖动的子节点中删除/创建父节点(Vuejs)
- android - Gradle 没有以正确的方式寻找依赖关系
- android - 以编程方式更改约束布局的边距