You need to enable JavaScript to run this app. Python如何从CSV词典中检索含指定顺序三个字符的单词
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从CSV词典中检索含指定顺序三个字符的单词

代码修改方案

修复后完整代码

import csv

def read_words(file_path):
    with open(file_path, encoding="utf-8") as f:
        lector = csv.reader(f)
        # 若CSV每行仅存1个单词,取每行第一个元素,若有多个单词可按需调整
        palabras = [p[0].strip() for p in lector if p]
    return palabras

file = "Diccionario.csv"
register = read_words(file)

def search_for_words_with(register, a, b, c):
    res = []
    for w in register:
        # 按顺序查找三个字符的位置
        idx_a = w.find(a)
        if idx_a == -1:
            continue
        # 从a的下一位开始找b
        idx_b = w.find(b, idx_a + 1)
        if idx_b == -1:
            continue
        # 从b的下一位开始找c
        idx_c = w.find(c, idx_b + 1)
        if idx_c != -1:
            res.append(w)
    return res

逻辑说明

  • 修复了原read_words函数的参数错误:原函数参数未被使用,依赖全局变量file,修改为接收文件路径作为入参,逻辑更合理
  • 修复了CSV读取的隐藏问题:csv.reader返回的每一行是列表格式,若CSV每行仅存1个单词,需要取列表第一个元素作为实际单词
  • 新增顺序校验逻辑:通过str.find()的第二个参数指定查找起始位置,确保a出现在b之前、b出现在c之前,满足顺序要求才会将单词加入结果

如果需要支持大小写不匹配的搜索,可以把查找逻辑修改为w.lower().find(a.lower()),三个字符的查找都做同样处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 20:33:02