將markdown文件轉換為html文件


首先當然是Typora自帶轉換啦:

image-20200816215751516

接下來是我所聽聞之(zhaung)方(bi)法有以下幾種

python環境工具之腳本大法【自csdn轉載】

可以將markdown文件通過python的一些庫函數較好的轉換成html文件

效果預覽

源碼預覽:

import mistune
import sys
import codecs
import os
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 md2html(s):
    with codecs.open(s, mode='r', encoding='utf-8') as mdfile:
        md_text = mdfile.read()
        extras = ['code-friendly', 'fenced-code-blocks', 'footnotes']
        renderer = HighlightRenderer()
        markdown = mistune.Markdown(renderer=renderer)
        html_text = markdown(md_text)
        html_text = html_text.replace('highlight', 'cnblogs_code ')
 
        html_name = '%s.html' % (s[:-3])
        with codecs.open(html_name, 'w', encoding='utf-8', errors='xmlcharrefreplace') as output_file:
            output_file.write(html_text)
 
 
def getAllFile(path, suffix='.'):
    "recursive is enable"
    f = os.walk(path)
    fpath = []
 
    for root, dir, fname in f:
        for name in fname:
            if name.endswith(suffix):
                fpath.append(os.path.join(root, name))
 
    return fpath
 
 
def convertAll(path):
    flist = getAllFile(path, ".md")
    for fname in flist:
        md2html(fname)
 
 
if __name__ == "__main__":
    path = ''
    if len(sys.argv) == 1:
        path = os.getcwd()
 
    elif len(sys.argv) == 2:
        path = sys.argv[1]
    else:
        print("error parameter")
        exit()
 
    convertAll(path)

該工具出自大神之手為將其轉換為html文件后上傳至博客園而寫,配合博客園的一些其他設置可以實現高亮代碼等多種功能

詳情請訪問

trouble shooting:

1、在安裝軟件時可能會遇到一些問題其實可能是因為python庫的依賴沒有安裝 比如mistune是python對md文件的支持,pygments是實現高亮代碼功能的庫函數 請使用python的包管理器來安裝它們

# pip install mistune
# pip install pygments
如果是python3的包管理器命令是pip3請這樣輸入
# pip3 install mistune
# pip3 install pygments

node環境工具之i5ting

該工具的一大特點是在左側欄將會生成各小結的目錄列表

效果預覽:

npm install i5ting_toc -g

如果覺得安裝太慢可以使用淘寶代理加速安裝工具cnpm來安裝(就是將所有npm換成cnpm就會自動代理加速了)

使用方法如下:

i5ting_toc -f <需要轉換的文件名>.md

此時會在目錄下生成preview文件夾,其中會有一個與markdown同名的html文件。

MarkdownMonster項目

該項目是一項大型的可以配合博客發布的軟件,其中真好有一項功能是將md文件轉換為html,不僅如此還可以實現互轉(即將html文件轉換為markdown文件的強大功能),其還可以通過api發布的模式來將md文件轉換為html文件后上傳至wordPress, Medium以及任何使用MetaWeblog API的博客平台。

感興趣的小伙伴請移步另一篇文章

如何批量上傳文章至各大博客平台(含markdown文件)

當然如果小伙伴不需要跟過花里胡哨的功能只是想讓md文件變為html文件使用上述兩種辦法應該就能滿足需要了。

MarkdownMonster的github項目地址


免責聲明!

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



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