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

如何将固定重复格式的.txt文件内容转换为指定列的.csv文件?

将重复格式的TXT转换为CSV的Python实现

实现思路

你的需求是把按固定字段重复的TXT内容转成结构化的CSV,核心是按条目分组提取字段值,再用Python标准库的csv模块安全写入(避免手动写文本导致的格式问题,比如内容含逗号、引号)。

示例输入TXT格式

假设你的TXT内容是这样的(每个条目4行一组):

Name: name_1
Error Text: some_text_1
Correct Text: some_text_2
Type of Error: some_text_3
Name: name_2
Error Text: some_text_4
Correct Text: some_text_5
Type of Error: some_text_6

完整代码实现

import csv

# 替换成你的输入文件名
input_file = "your_input.txt"
output_file = "output.csv"

# CSV表头,和你的字段一一对应
csv_headers = ["Name", "Error Text", "Correct Text", "Type of Error"]

with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', newline='', encoding='utf-8') as outfile:
    # 初始化CSV写入器
    csv_writer = csv.writer(outfile)
    # 先写入表头
    csv_writer.writerow(csv_headers)
    
    current_entry = []
    for line in infile:
        # 清理每行:去掉首尾空格和换行符
        cleaned_line = line.strip()
        # 跳过空行(如果TXT里有空行的话)
        if not cleaned_line:
            continue
        
        current_entry.append(cleaned_line)
        # 收集到4行就处理一个完整条目
        if len(current_entry) == 4:
            # 提取每个字段的值:分割第一个冒号,取后面的内容
            name = current_entry[0].split(':', 1)[1].strip()
            error_text = current_entry[1].split(':', 1)[1].strip()
            correct_text = current_entry[2].split(':', 1)[1].strip()
            error_type = current_entry[3].split(':', 1)[1].strip()
            
            # 写入CSV一行
            csv_writer.writerow([name, error_text, correct_text, error_type])
            # 清空列表,准备下一个条目
            current_entry = []

关键细节说明

  1. 用csv模块而非直接写文本:如果你的字段值里包含逗号、双引号,手动写文本会破坏CSV格式,csv.writer会自动处理这些特殊字符。
  2. split(':', 1)的作用:只分割第一个冒号,避免字段值里有冒号时(比如Error Text写了Error: missing comma)被错误分割。
  3. newline='':这是Python官方推荐的写法,避免在Windows系统下生成的CSV出现多余空行。
  4. 处理空行:如果你的TXT文件里有空白行,代码会自动跳过,不影响条目分组。

注意事项

  • 确保你的TXT文件每个条目严格是4行一组,如果有缺失行或格式混乱,代码可能无法正确处理,建议先检查输入文件的格式一致性。
  • 如果字段值里包含换行符,需要额外处理,但一般这种场景很少见,当前代码足以覆盖你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:55:31