You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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')

修改说明

  1. 修复语法错误:原代码中input的参数缺少字符串引号,添加引号后才能正常接收用户输入。
  2. 调整匹配逻辑:
    • 原代码的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:50:51