近年来Markdown的普及率越来越高,不会写两句latex都不好意思写论文。。。然而也不知道Github是不是想给我们这些程序员省省脑子,这么多年来一直不支持在README.md中渲染公式。因此如果你用Typora或者CSDN写了一份带公式的Markdown,想要作为Github的README文件时就会发现公式全保留了latex格式,没有渲染。
用过知乎做笔记的小伙伴应该知道知乎有一个把latex渲染成图片的api:https://www.zhihu.com/equation?tex=
那么能否批量把用$$
或$
标记的公式转换成图片呢?
自然我们会想到python和正则表达式
只要用正则匹配出$$
内的latex,再进行url编码后在前面加上![](https://www.zhihu.com/equation?tex=
,在后面补上)
就好了
完整代码如下:
import re
from urllib import parse
# 匹配数学块,DOTALL匹配多行
multi_line_formula_pattern = re.compile(r'\$\$(?P<value>.*?)\$\$', re.DOTALL)
# 匹配行内公式
inline_formula_pattern = re.compile(r'\$(?P<value>.*?)\$', re.S)
# 数学块转换
def MtoImage(matched):
encoded = parse.quote(matched.group('value'))
return '\n![](https://www.zhihu.com/equation?tex=' + encoded + ')\n'
# 行内公式转换
def StoImage(matched):
encoded = parse.quote(matched.group('value'))
return '![](https://www.zhihu.com/equation?tex=' + encoded + ')'
with open(r"README.md", encoding='utf-8') as md_file:
text = md_file.read()
text2 = re.sub(multi_line_formula_pattern, MtoImage, text)
text3 = re.sub(inline_formula_pattern, StoImage, text2)
with open("output.md", "w", encoding='utf-8') as output:
output.write(text3)