Using Python markdown to generate HTML

Time:2020-3-25

More and more people like to use markdown to write documents, which is simpler and more convenient than doc, and can render and output their favorite styles.
The document markdown written in the development process is convenient for the management of version control tools such as SVN and GIT.

Install Python markdown and do the syntax conversion from markdown to HTML

pip install markdown

Install pysegments to highlight syntax

pip install Pygments

Execute the following command to generate a default syntax highlighting CSS file. For more information, please refer to the pysegments project website

pygmentize -S default -f html > default.css

The current GitHub style stylesheet, where the code is downloaded and saved as github.css.

Full code:

# -*- coding: utf-8 

import markdown
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')

def md2html(mdstr):
    exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc']

    html = '''
    <html lang="zh-cn">
    <head>
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <link href="default.css" rel="stylesheet">
    <link href="github.css" rel="stylesheet">
    </head>
    <body>
    %s
    </body>
    </html>
    '''

    ret = markdown.markdown(mdstr,extensions=exts)
    return html % ret



if __name__ == '__main__':

    if len(sys.argv) < 3:
        print('usage: md2html source_filename target_file')
        sys.exit()

    infile = open(sys.argv[1],'r')
    md = infile.read()
    infile.close()

    
    if os.path.exists(sys.argv[2]):
        os.remove(sys.argv[2])


    outfile = open(sys.argv[2],'a')
    outfile.write(md2html(md))
    outfile.close()

    print('convert %s to %s success!'%(sys.argv[1],sys.argv[2]))

Save the code on as md2html.py and execute

python md2html.py test.md test.html

Recommended Today

Decision tree classifier and pruning based on Python

By angel DasCompile | VKSource: toward Data Science introduce Decision tree classifier is a supervised learning model, which is very useful when we are concerned about interpretability. Decision trees decompose data by making decisions based on multiple problems at each level Decision tree is one of the common algorithms for classification. To better understand it, […]