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

Python从结构化文本文件提取指定条件名称列表问题求解

问题原因
  • 路径配置与读取逻辑错误:代码中file变量仅填写了占位文本,未替换为实际文件路径,会导致读取内容为空;且仅使用readline()读取了文件单行内容,没有遍历全量行匹配记录,会直接触发No num found输出。
  • 逻辑链路断裂:即使成功匹配到ALPHA对应的Output行拿到编号,代码也没有遍历全量文件查找该编号对应的Input记录,仍然在对第一行内容做Input判断,第一行类型为Output,永远不可能命中该分支。
  • 语法错误:liste.append(contenu.split(";")[0] 缺少右括号,运行会直接抛出语法异常。
  • 未处理空白字符:文件每行末尾自带换行符、空格,直接匹配会导致字段校验失败。
正确实现方案

实现逻辑:先遍历全量行提取ALPHA+Output对应的编号,再二次遍历筛选编号匹配+类型为Input的名称,自动去重。

file = "替换为你的实际文件路径"
target_name = "ALPHA"

def search_new_name():
    # 第一步:提取目标编号
    target_num = None
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            name, num, typ = line.split(";")
            if name == target_name and typ == "Output":
                target_num = num
                break
    if not target_num:
        print("No num found")
        return []
    
    # 第二步:筛选符合条件的名称
    res = []
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            name, num, typ = line.split(";")
            if num == target_num and typ == "Input" and name not in res:
                res.append(name)
    if not res:
        print("No new name found")
        return []
    return res

liste_new_name = search_new_name()
print(liste_new_name)

运行后输出结果为['BETA', 'CHARLIE'],符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:51:00