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

如何将含多行公式的TXT文件转换为CSV并使公式保持单行?

解决TXT转CSV时多行公式合并问题

问题场景

原始TXT数据以|分隔,其中部分行的Formula字段包含多行内容(被~BeginFormula~和~EndFormula~标记包裹),直接用pandas.read_csv读取时,公式内的换行会被识别为新的数据行,导致格式混乱。

原始数据示例:

ID|Name1|Description|Name2|Type|Rate|Sign|B|C|P|U|Member|Formula
100|100|100 Cash|All|B|Rate|D|Y|Y||DATA|Total|
100|100|100 Cash|All|B|Rate|D|Y|Y||DATA|Total|
110|110|110 Expense|P|Average|D|Y|Y||DATA|Header|~BeginFormula~(expr(if rpt then 
if MemberIs([V]:[O]) or MemberIs([V]:[R]) or MemberIs([V]:[F]) then
if [cost] <> 0 or [cost] = -100 then 
[cost] = ([c] * [a]) + [a];
endif
endif
endif))~EndFormula~
800|sale|Dsale|bs|BL|Rate|C|Y|Y||DATA|Tax|~BeginFormula~(expr([sale] = 0))~EndFormula~

之前尝试的代码未处理多行公式:

import pandas as pd

read_file = pd.read_csv (r'C:\Users\text.txt', 
sep="|",error_bad_lines=False)
read_file.to_csv (r'C:\Users\TestOutput.csv', index=None)

解决方案

步骤1:预处理文本,合并公式内的多行

先遍历原始TXT文件,识别公式区域并将其中的换行替换为空格,确保每个数据行是完整的一行:

input_path = r'C:\Users\text.txt'
processed_path = r'C:\Users\processed_text.txt'

with open(input_path, 'r', encoding='utf-8') as f_in, open(processed_path, 'w', encoding='utf-8') as f_out:
    in_formula = False
    for line in f_in:
        # 移除行尾的换行符,避免后续拼接混乱
        stripped_line = line.rstrip('\n')
        if '~BeginFormula~' in stripped_line:
            in_formula = True
            f_out.write(stripped_line)
        elif '~EndFormula~' in stripped_line:
            in_formula = False
            # 公式结束后添加换行,标记完整数据行
            f_out.write(stripped_line + '\n')
        elif in_formula:
            # 公式内的行,用空格连接,保留内容
            f_out.write(' ' + stripped_line.strip())
        else:
            # 普通数据行直接写入
            f_out.write(stripped_line + '\n')

步骤2:转换为CSV格式

使用pandas读取预处理后的文件,转换为CSV:

import pandas as pd

# 读取预处理后的文本,指定分隔符为|
df = pd.read_csv(processed_path, sep='|')
# 导出为CSV,默认用逗号分隔,自动处理含空格的字段
df.to_csv(r'C:\Users\TestOutput.csv', index=None)

关键说明

  • 利用~BeginFormula~和~EndFormula~作为公式区域的标记,精准识别需要合并的多行内容,避免误处理其他正常换行。
  • 如果需要保留公式内的换行,可以将代码中替换的空格改为\n,pandas导出CSV时会自动用引号包裹包含换行的字段,符合CSV格式规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:50:52