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

Python提取student.txt学生数据写入CSV及现有代码问题修复

修正后的实现方案

核心修改点

  • 移除了无差别捕获异常的try/pass逻辑,通过判断行内是否包含->过滤无效行
  • 删除冗余的flag校验逻辑,简化属性匹配流程
  • 补充遍历结束后最后一个学生的属性写入逻辑,避免数据丢失
  • 采用Python内置csv模块写入文件,保证CSV格式符合标准,无多余逗号、换行错误
  • 修正属性绑定逻辑,确保所有sibling、hobby数据正确关联到对应姓名

完整代码

import csv

# 初始化变量
current_name = None
current_siblings = []
current_hobbies = []
result = []

# 读取源文件
with open("student.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        # 过滤不含->的无效行
        if "->" not in line:
            continue
        key, value = line.split("-> ", 1)
        value = value.strip().rstrip(",")
        
        if key == "name":
            # 遇到新姓名,保存上一个学生的信息
            if current_name is not None:
                result.append({
                    "Name": current_name,
                    "Siblings": "\n".join(current_siblings) if current_siblings else "N/A",
                    "Hobbies": " ".join(current_hobbies) if current_hobbies else "N/A"
                })
            # 重置当前学生的属性
            current_name = value
            current_siblings = []
            current_hobbies = []
        elif key == "sibling":
            current_siblings.append(value)
        elif key.startswith("hobby"):
            current_hobbies.append(value)
    
    # 保存最后一个学生的信息
    if current_name is not None:
        result.append({
            "Name": current_name,
            "Siblings": "\n".join(current_siblings) if current_siblings else "N/A",
            "Hobbies": " ".join(current_hobbies) if current_hobbies else "N/A"
        })

# 写入CSV文件
with open("student.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["Name", "Siblings", "Hobbies"])
    writer.writeheader()
    writer.writerows(result)

输出的student.csv效果

Name,Siblings,Hobbies
Alice,N/A,N/A
Sam,"Kate
Luke",football games
Ramsay,N/A,dance swimming jogging

注:CSV中包含换行的字段会自动用双引号包裹,符合CSV标准规范,用Excel/WPS打开时会自动显示为多行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:45:03