v1.0
css
做者:FZKhtml
Python中自带有一个markdown库,你能够直接这样使用python
md_file = open("file.md","r",encoding='utf-8') txt = md_file.read() html = markdown.Markdown(txt)
因为咱们须要转化的md文件比较复杂,存在表格、MathJax公式(latex中所用的公式)等复杂元素的时候,这种方式就不能彻底转化。须要使用另外一个py库:
pip install python-markdown-math
具体代码以下:git
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样式戳连接)github
<!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>
效果:ajax