【技术博客】利用Python将markdown文档转为html文档

利用Python将markdown文档转为html文档

v1.0

作者:FZK


元素简单的md文件

Python中自带有一个markdown库,你可以直接这样使用

md_file = open("file.md","r",encoding='utf-8')
txt = md_file.read()
html = markdown.Markdown(txt)

较为复杂的md文件

由于我们需要转化的md文件比较复杂,存在表格、MathJax公式(latex中所用的公式)等复杂元素的时候,这种方式就不能完全转化。需要使用另一个py库:
pip install python-markdown-math
具体代码如下:

import markdown
from mdx_math import MathExtension

html_head_file = open("html_head.txt","r",encoding='utf-8')
html_head = html_head_file.read()
html_head_file.close()

html_tail = "\n</body>\n</html>"
html_body = ""

html_body_file = open("file.md","r",encoding='utf-8')
html_body_txt = html_body_file.read()
html_body_file.close()

# 所支持的复杂元素
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc',MathExtension(enable_dollar_delimiter=True)]

md = markdown.Markdown(extensions = exts)
html_body = md.convert(html_body_txt)

html = html_head + html_body + html_tail
html_file = open("file.html","w",encoding='utf-8')
html_file.write(html)
html_file.close()

其中html_head_file包含对MathJax的支持,以及样式的优化(我们使用了github中的md样式戳链接)

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML' async></script>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
<link href="github.css" rel="stylesheet">
</head>

<body>

效果:

1632388-20190617174120635-1941699941.png

转载于:https://www.cnblogs.com/hardchoice/p/11041139.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值