python3自带了markdown模块,没有的话可以用:

pip3 install markdown 安装

下面是用python3转换markdown文件的方法:

import os,time,sys
import markdown
def markdown2html(markdown_text):
    html = markdown.markdown(
        markdown_text,
        output_format="html5",
        extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.toc',
            'markdown.extensions.codehilite',
            'markdown.extensions.meta'
        ]
    )
    return html
def saveBin(filename, content):
    f = open(filename,mode="wb+")
    f.write(content)
    f.flush()
    f.close()
def fConvert1(infilename, outfilename):
    fileOrgin = open(infilename)
    hin=""
    hout=""
    for p in fileOrgin:
        hin = "%s%s"%(hin,p)
    hout = markdown2html(hin)
    htmltemplate = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
    {{}}
    </body>
    '''
    hout= htmltemplate.replace("{{}}", hout)
    saveBin(outfilename, hout.encode())
def main():
    if(len(sys.argv)>1):
        infilename= sys.argv[1]
        outfilename=  infilename+".html"
        fConvert1(infilename,outfilename)
if __name__ == '__main__':
    main()

调用的时候

$python3 convendor.py README.md

可以在相同目录下生成README.md.html文件。

本文由tweetyf.org原创,转载请注明出处。