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

如何编写Python函数从字符串列表中搜索匹配指定关键词的内容

Python字符串列表搜索函数问题修复方案

问题核心原因

  • 循环变量命名冲突:循环中使用了和入参列表同名的data作为遍历变量,会覆盖原列表对象,属于逻辑隐患。
  • 匹配逻辑错误:原代码的判断条件if data in search_words是校验「当前遍历的完整字符串是否属于搜索词列表」,你的测试数据中所有字符串均为长文本,不可能完全匹配earnings、sales两个短搜索词,因此返回空列表。

修复后代码

基础写法

def search_words(data, search_words):
    keep = []
    # 重命名循环变量避免冲突
    for text_item in data:
        # 校验当前文本是否包含任意一个目标搜索词
        for target_word in search_words:
            if target_word in text_item:
                keep.append(text_item)
                # 匹配到一个即跳出,避免同一条文本重复加入结果
                break
    return keep

简洁列表推导式写法

def search_words(data, search_words):
    return [item for item in data if any(word in item for word in search_words)]

运行结果

使用你提供的测试数据执行print(search_words(data=data, search_words=words)),输出结果为:

['SHOP earnings for Q1 are up 5%', 'Subscriptions at SHOP have risen to all-time highs, boosting sales', 'TSLA execs hint at a decline in earnings following a capital expansion program']

可选优化

如果需要实现大小写不敏感的匹配,可以将判断条件修改为if target_word.lower() in text_item.lower()即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:27:05