用python给markdown文档加空行

在文本格式化过程中,我们通常会在行与行之间添加一个空行,以提升文档的阅读体验,使其外观更加整洁。

若您处理的文档篇幅较短,手动添加空行也是一个可行的选择。

此外,为了简化这一过程,您可以采用以下Python代码,确保文档中每两行之间恰好有一个空行。

以下代码,把需要处理的文本,保存在 "input.md" 里,把这个文件放在 python 运行的根目录,python 会在同样位置,生成一个清洗好之后的 "output.md" 文件。

dart 复制代码
def process_text(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    with open(output_file, 'w', encoding='utf-8') as file:
        for i in range(len(lines)):
            line = lines[i].rstrip('\n')
            if line:  # 如果当前行不为空
                file.write(line + '\n')  # 添加行和换行符
                # 检查下一行是否为空,如果不为空,则在两行之间添加一个空行
                if i + 1 < len(lines) and lines[i + 1].strip():
                    file.write('\n')
            else:  # 如果当前行为空
                if i + 1 < len(lines) and lines[i + 1].strip():  # 如果下一行不为空
                    file.write('\n')  # 在连续空行之间只添加一个空行

input_file = 'input.md'  # 输入文件的路径
output_file = 'output.md'  # 输出文件的路径
process_text(input_file, output_file)
相关推荐
ebiobiz1 小时前
基于 GD32 Embedded Builder (GEB) 与 Nimmake 的 MCU 工程搭建指南
c++·python·单片机·嵌入式硬件·mcu
老歌老听老掉牙2 小时前
穿越时空的物流密码:VRP与VRPTW的深度剖析及实战求解
python·物流·vrp
FYKJ_20102 小时前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
ShyanZh2 小时前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
小静AI工程实验室2 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
xzal122 小时前
GESP Python笔记
笔记·python·算法
半日闲dusknook3 小时前
我给 AI 写了个「音频编译器」:把「听起来还行」变成 PASS/FAIL
python
在世修行3 小时前
干货:信号槽
python·信号槽
Wx-bishekaifayuan3 小时前
springboot生活易购超市管理系统54086-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
数字融合3 小时前
透明化数字孪生智慧养老平台运维服务项目
人工智能·python·virtualenv