首先你需要一个markdown解析器
比如有常见的markdown和markdown2,其他的可以参考这个网站的评价
我选择了mistune,自己继承写一个渲染的Renderer
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mistune
import sys
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
class HighlightRenderer(mistune.Renderer):
def block_code(self, code, lang):
if not lang:
return '
<pre><code>%s</code></pre>
' %
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter()
return highlight(code, lexer, formatter)
def main(argv):
name = argv[0]
md_name = '%s.md' % (name)
outfile = '%s.html' % (name)
with open(md_name) as mdfile:
md_text = mdfile.read()
rd = HighlightRenderer()
markdown = mistune.Markdown(renderer=rd)
html = markdown(md_text)
# 为了避免中文乱码 以及添加高亮样式
head_css = '<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
'
css_name = "code.css"
code_css = '<link rel="stylesheet" href="' + css_name
+ '" type="text/css"/>
'
code_css = head_css + code_css
with open(outfile, 'w') as output:
output.write(code_css + html)
if __name__ == "__main__":
main(sys.argv[1:])
利用pygments的命令生成特定主题的css:
pygmentize -f html -a .codehilite -S monokai > code.css
之后运行这个python文件,假设markdown文件是data.md,运行 python solve.py data 即可
具体还有什么样式可以在 pygments网站看