用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)
相关推荐
mahuifa7 分钟前
OpenCV 开发 -- 图像基本处理
人工智能·python·opencv·计算机视觉
一个java开发41 分钟前
distributed.client.Client 用户可调用函数分析
大数据·python
eqwaak01 小时前
Matplotlib 动态显示详解:技术深度与创新思考
网络·python·网络协议·tcp/ip·语言模型·matplotlib
007php0071 小时前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 将 Pandas DataFrame 转换为 Excel
python·json·excel·pandas·csv·aspose·dataframe
flashlight_hi1 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
java1234_小锋1 小时前
Scikit-learn Python机器学习 - 特征预处理 - 归一化 (Normalization):MinMaxScaler
python·机器学习·scikit-learn
星空的资源小屋2 小时前
网易UU远程,免费电脑远程控制软件
人工智能·python·pdf·电脑
IMER SIMPLE2 小时前
人工智能-python-深度学习-神经网络-MobileNet V1&V2
人工智能·python·深度学习
eleqi2 小时前
Python+DRVT 从外部调用 Revit:批量创建楼板
python·系统集成·revit·外部调用·drvt·自动化生产流水线