import re

md_path = 'md.txt'
out_path = 'out.txt'

with open(md_path, 'r', encoding='utf-8') as f:
    text = f.read()

text = text.replace('[TOC]', '@[TOC](文章目录)')
text = text.replace('[toc]', '@[TOC](文章目录)')

p_inline = re.compile(r'`(?P<formula>\$[\s\S]+?\$)`', flags=re.S)  # 去掉行内公式两端的``
text = p_inline.sub(lambda x: x.group('formula'), text)  # 把text中匹配到的子串,都按第一个参数(函数)处理


rm_tag = False  # 是否删除公式的编号
if rm_tag:
    p_block = re.compile(r'```math(?P<formula>.+?)\\tag[\s\S]+?```', flags=re.DOTALL)
else:
    p_block = re.compile(r'```math(?P<formula>.+?)```', flags=re.DOTALL)  # 将块公式```math f```改为$$f$$
text = p_block.sub(lambda x: '$$' + x.group('formula') + '$$', text)


with open(out_path, 'w', encoding='utf-8') as f:
    f.write(text)

print(text)

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐