Python:如何检测输入字符串包含列表中的多词短语
问题
我现有如下Python代码:
intents = ['hello world', 'random string'] phrase = input(Enter your message: ) if phrase in intents: print('Found')
当前代码仅支持完全匹配intents中的字符串,我希望实现:当输入的短语(如"hello world this python")包含intents中的任意一个完整多词短语时,也能输出'Found',请问该如何修改?
解决方案
修改后的代码
intents = ['hello world', 'random string'] phrase = input("Enter your message: ") if any(intent in phrase for intent in intents): print('Found')
修改说明
- 修复语法错误:原代码中
input的参数缺少字符串引号,添加引号后才能正常接收用户输入。 - 调整匹配逻辑:
- 原代码的
phrase in intents仅检查输入内容是否与intents中的某一项完全相等。 - 替换为
any(intent in phrase for intent in intents)后,会遍历intents中的每个短语,只要有一个短语作为完整子串出现在输入内容中,就会返回True,执行print('Found')。
- 原代码的
举个例子:
- 输入
hello world this python时,'hello world'是输入内容的子串,满足条件,输出Found。 - 输入
random string test时,'random string'匹配成功,同样输出Found。 - 输入
hello或random时,因为不是intents中的完整多词短语,不会触发匹配。
内容的提问来源于stack exchange,提问作者Ibrahim Ali
相关产品推荐
相关产品推荐

