用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)
相关推荐
满怀10155 分钟前
【Flask全栈开发指南】从零构建企业级Web应用
前端·python·flask·后端开发·全栈开发
PWRJOY6 分钟前
Flask-SQLAlchemy_数据库配置
数据库·python·flask
mahuifa22 分钟前
Qt图表绘制(QtCharts)- 性能优化(13)
python·qt·pyside6·开发经验·qtchart
Bugabooo1 小时前
python打卡DAY22
开发语言·python
低维歌者1 小时前
python训练营day27
java·开发语言·python
微刻时光1 小时前
影刀处理 Excel:智能工具带来的高效变革
人工智能·python·低代码·自动化·excel·rpa·影刀rpa
大帅不是我1 小时前
Python多进程编程执行任务
java·前端·python
Fu_lucas1 小时前
Python Logging 模块完全指南
开发语言·python
Eiceblue1 小时前
Python 在Excel单元格中应用多种字体样式
开发语言·vscode·python·pycharm·excel
Superstarimage3 小时前
使用conda创建python虚拟环境,并自定义路径
windows·python·conda