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

如何在Python脚本中集成.lower()函数实现不区分大小写关键词检测?

解决不区分大小写的关键词检测问题

要实现不区分大小写的关键词检测,核心是统一输入文本和目标关键词的大小写后再进行包含性判断,以下是两种简洁的修改方案:

方案一:实时转换关键词与输入的大小写

直接在判断逻辑中,将输入和每个关键词都转为小写后再比较:

terms = ["test1", "test2"]
user_input = input()
lower_input = user_input.lower()

if all(term.lower() in lower_input for term in terms):
    print("Both words were found")
else:
    print("Couldn't find required words")

方案二:提前转换关键词列表的大小写

如果关键词列表固定,可以提前将所有关键词转为小写(仅转换一次),效率更高:

terms = ["test1", "test2"]
# 提前把关键词批量转成小写
lower_terms = [term.lower() for term in terms]
# 输入直接转小写
user_input = input().lower()

if all(term in user_input for term in lower_terms):
    print("Both words were found")
else:
    print("Couldn't find required words")

关键改动说明

  • 将原变量名raw_input改为user_input,避免与Python旧版内置函数名称混淆;Variable改为term,命名更贴合语义。
  • 通过.lower()方法将输入文本和关键词统一转为小写,彻底消除大小写差异对匹配结果的影响。
  • 两种方案逻辑等价,可根据关键词列表的使用场景任选其一。

内容的提问来源于stack exchange,提问作者Cabbage

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:15:27