用python+正则 将markdown中的公式批量转换为图片

近年来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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值