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

如何将含缺失占位符的文本文件转为CSV并处理缺失项?

处理带缺失占位符的文本转CSV的最简方法

你要处理的文本数据以-为分隔符,存在缺失值占位(比如连续-之间的空内容、行尾的空占位),示例数据如下:

apple - red - sweet - fruit - apple pie    
carrot - orange - - vegetable - carrot cake     
eggplant - purple - watery- vegetable -        

原代码存在两个问题:

  • 模块拼写错误:import cvs应为import csv
  • 直接用split("-")会导致字段带多余空格,且缺失占位的处理不规范,可能引发CSV列错位

最简处理方法是在分割后对每个字段做去除首尾空格的处理,同时确保每行字段数与表头一致,修改后的代码如下:

import csv
with open('data.txt', 'r') as file:
    stripped = (line.strip() for line in file)
    # 分割后对每个字段去除首尾空格,空占位会转为空字符串
    lines = ([field.strip() for field in line.split("-")] for line in stripped if line)
    with open('text.csv', 'w', newline='') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('name', 'color', 'taste', 'category', 'recipe'))
        writer.writerows(lines)

关键处理点:

  • [field.strip() for field in line.split("-")]:分割后逐个清理字段的首尾空格,原数据中-之间的空占位(比如orange - - vegetable里的空)会被转为空字符串,符合CSV缺失值的存储规范
  • 添加newline='':避免Windows系统下生成的CSV出现多余空行
  • 修正模块拼写错误:csv而非cvs

这样处理后,生成的CSV中缺失占位会被正确识别为空值,且所有字段无多余空格,列数与表头完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:57:43