用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)
相关推荐
做怪小疯子7 小时前
华为笔试0429
python·numpy
Warson_L8 小时前
Dictionary
python
寒山李白10 小时前
解决 python-docx 生成的 Word 文档打开时弹出“无法读取内容“警告
python·word·wps·文档·docx·qoder
2401_8323655210 小时前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
Sirius.z11 小时前
第J3周:DenseNet121算法详解
python
2301_7796224111 小时前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
2301_7662834411 小时前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python
小康小小涵12 小时前
基于ESP32S3实现无人机RID模块底层源码编译
linux·开发语言·python
lzjava202413 小时前
Python的函数
开发语言·python
Awesome Baron13 小时前
skill、tool calling、MCP区别
开发语言·人工智能·python