用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)
相关推荐
是小蟹呀^几秒前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好10 分钟前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
王夏奇27 分钟前
pythonUI界面弹窗设置的几种办法
python·ui
ZhengEnCi40 分钟前
P2B-Python可迭代对象完全指南-从列表到生成器的Python编程利器
python
萌萌站起1 小时前
Vscode 中 python模块的导入问题
ide·vscode·python
是小蟹呀^2 小时前
【总结】提示词工程
python·llm·prompt·agent
YBAdvanceFu2 小时前
从零构建智能体:深入理解 ReAct Plan Solve Reflection 三大经典范式
人工智能·python·机器学习·数据挖掘·多智能体·智能体
王夏奇2 小时前
python中的__all__ 具体用法
java·前端·python
王夏奇2 小时前
pycharm中3种不同类型的python文件
ide·python·pycharm
小陈的进阶之路2 小时前
Selenium 滑动 vs Appium 滑动
python·selenium·测试工具·appium