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

如何用Python仅移除文本中的单个空行以整理内容?

移除单个空行,保留多个空行的Python实现

你需要移除文本中的单个空行(连续两个换行符),但保留多个空行(连续三个及以上换行符),原代码data = open('data.txt').read().replace('\n', '')会删除所有换行,完全不符合需求,这里提供两种可行方案:

方案一:正则表达式替换(推荐)

正则能精准匹配连续换行符,根据匹配长度做对应替换,代码简洁高效:

import re

# 读取文件内容
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 处理逻辑:连续2个换行→替换为1个;连续3个及以上换行→替换为2个
processed_content = re.sub(
    r'\n{2,}',
    lambda match: '\n' if len(match.group()) == 2 else '\n\n',
    content
)

# 写入处理后的文件(可选择覆盖原文件或写入新文件)
with open('processed_data.txt', 'w', encoding='utf-8') as f:
    f.write(processed_content)

方案二:逐行遍历处理

如果不想依赖正则,可以通过逐行遍历并标记状态实现:

processed_lines = []
prev_line_empty = False

with open('data.txt', 'r', encoding='utf-8') as f:
    for line in f:
        stripped_line = line.rstrip('\n')
        if not stripped_line:
            if not prev_line_empty:
                # 首次遇到空行,标记状态,不添加(移除单个空行)
                prev_line_empty = True
            else:
                # 连续空行,保留当前空行
                processed_lines.append('')
                prev_line_empty = False
        else:
            # 非空行,重置空行标记,直接添加
            prev_line_empty = False
            processed_lines.append(stripped_line)

# 拼接处理后的内容
processed_content = '\n'.join(processed_lines)

# 写入文件
with open('processed_data.txt', 'w', encoding='utf-8') as f:
    f.write(processed_content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:33