利用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>
效果: