python: 用pygments給markdown文檔染色


首先你需要一個markdown解析器

比如有常見的markdown和markdown2,其他的可以參考這個網站的評價

我選擇了mistune,自己繼承寫一個渲染的Renderer

mistune的doc也有提及基本寫法


#!/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 '\n<pre><code>%s</code></pre>\n' % \
                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" />\n'
        css_name = "code.css"
        code_css = '<link rel="stylesheet" href="' + css_name \
            + '" type="text/css"/>\n'
        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網站

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM