近年来Markdown的普及率越来越高,不会写两句latex都不好意思写论文。。。然而也不知道Github是不是想给我们这些程序员省省脑子,这么多年来一直不支持在README.md中渲染公式。因此如果你用Typora或者CSDN写了一份带公式的Markdown,想要作为Github的README文件时就会发现公式全保留了latex格式,没有渲染。
用过知乎做笔记的小伙伴应该知道知乎有一个把latex渲染成图片的api:https://www.zhihu.com/equation?tex=
那么能否批量把用$$或$标记的公式转换成图片呢?
自然我们会想到python和正则表达式
只要用正则匹配出$$内的latex,再进行url编码后在前面加上就好了
完整代码如下:
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\n'
# 行内公式转换
def StoImage(matched):
encoded = parse.quote(matched.group('value'))
return ''
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)
本文介绍了一种方法,利用Python和正则表达式批量将Markdown中的LaTeX公式转换为知乎提供的图片链接,以便在不支持公式渲染的平台如Github的README.md中使用。通过匹配$$和$包裹的公式,然后调用知乎的API,可以将公式转为可显示的图片,解决了Markdown公式显示问题。

4216

被折叠的 条评论
为什么被折叠?



