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

Python中合并文本文件内换行拆分字段的问题求助

解决跨换行的表格元素拆分问题

问题分析

你的TXT表格用|作为分隔符,但部分元素因换行被错误拆分(比如just some times被拆成两个元素),且换行符并非标准\n,需要合并这些跨换行的元素并正确提取表格数据。

解决方案代码

with open("ridotto.txt", encoding='latin-1') as f:
    processed_rows = []
    current_row = []
    for line in f:
        stripped_line = line.strip()
        # 跳过分隔线
        if stripped_line.startswith("---"):
            continue
        # 判断是否为新的表格行(以|开头)
        if stripped_line.startswith("|"):
            # 保存上一行数据(如果存在)
            if current_row:
                processed_rows.append(current_row)
            # 拆分新行并过滤空元素
            current_row = [part.strip() for part in stripped_line.split("|") if part.strip()]
        else:
            # 将当前行内容追加到上一行的最后一个元素
            if current_row:
                current_row[-1] += " " + stripped_line
    # 保存最后一行数据
    if current_row:
        processed_rows.append(current_row)

# 转换成一维列表(按需使用)
flat_list = [item for row in processed_rows for item in row]
print(flat_list)

代码说明

  1. 过滤分隔线:直接跳过由---组成的分隔行,避免干扰数据处理。
  2. 识别新行:以|开头的行是新的表格行,按|拆分后过滤掉空元素(因行首的|会产生空元素),初始化当前行数据。
  3. 合并跨换行元素:不以|开头的行属于上一行最后一个元素的换行内容,直接追加到上一行末尾元素,用空格连接。
  4. 兼容非标准换行符:for line in f会自动处理\r、\r\n等非标准换行符,无需额外处理。

执行结果

处理后得到的一维列表为:
['apple', 'very good', 'every day', 'fruit', 'chocolate', 'not so good', 'just some times', 'snack', 'bread', 'good', 'every day', 'whole', 'carbs']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:15:33