前言
用markdown做笔记或者写文档时,会涉及到标题的序号。虽然Typora有相关插件,但是导出markdown时,序号不能一起导出。因此需要自动化实现添加标题序号。
要求
实现效果
思路
Python源码
import re
def replace_title_num(markdown_src, markdown_dst):
"""
替换标题序号
:param markdown_src: markdown源文件
:param markdown_dst: markdown目标文件
:return:
"""
with open(markdown_src, 'rb') as f:
txt = f.read().decode()
# 默认6个标题等级
heading_level = [0] * 7
# 正则表达式编译标题格式,必须是 1-6个#和空格开始
head_pattern = re.compile("^(#{1,6}) ")
new_markdown = []
for line in txt.splitlines():
result = re.search(head_pattern, line)
if not result:
new_markdown.append(line)
continue
level = len(result.group(1))
heading_level[level] += 1
# int 转 str
num_str = map(str, heading_level[1:level+1])
# 拼接并替换字符串
title = f"{result.group(1)} {'.'.join(num_str)}."
heading_level[level+1:] = [0]*(7-level)
line = line.replace(result.group(1), title)
new_markdown.append(line)
new_content = "\n".join(new_markdown)
with open(markdown_dst, "w", encoding='utf8') as f:
f.write(new_content)
if __name__ == '__main__':
markdown_src = r"E:\Code\markdown\数据科学2.md"
markdown_dst = r"E:\Code\markdown\数据科学_带序号.md"
replace_title_num(markdown_src, markdown_dst)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。