Python下將Markdown轉(zhuǎn)為HTML

markdown 包進行轉(zhuǎn)換。

pip install Markdown

參考文檔:https://python-markdown.github.io/

基本用法

使用 markdown.markdown() 函數(shù)將 markdown 字符串轉(zhuǎn)換為 html 字符串俺夕。

import codecs, markdown

# 讀取 markdown 文本
input_file = codecs.open("some_file.md", mode="r", encoding="utf-8")
text = input_file.read()

# 轉(zhuǎn)為 html 文本
html = markdown.markdown(text)

# 保存為文件
output_file = codecs.open("some_file.html", mode="w", encoding="utf-8")
output_file.write(html)

注意:markdown包的輸入和輸出都只采用 utf-8 編碼题造。

使用擴展

markdown.markdown() 函數(shù)的參數(shù) extensions 指定擴展列表悼瓮。

擴展列表的每一項為擴展類實例或擴展名(無參數(shù)擴展):

ext1_instance = ExtClass1()
ext2_str = "ExtClass2()"
extensions=[ext1_instance, ext2_str]

在構(gòu)造擴展實例時可對擴展進行配置:

from markdown.extensions import Extension

class MyExtClass(Extension):
    # define your extension here...
    def __init__(self, option):
        # ...

markdown.markdown(text, extensions=[MyExtClass(option='value')])

其他參數(shù)和用法

markdown.markdown 函數(shù)還可設置以下參數(shù):

  1. output_format: 參數(shù)默認值為 xhtml,可改為 html5告喊。
  2. tab_length: 源文件中tab字符代表的空格數(shù)闪檬,默認值為4。

每次調(diào)用 markdown.markdwon 函數(shù)時氛悬,都創(chuàng)建了一個 markdown.Markdown 類實例则剃。當處理大量文件時,為提高效率如捅,可手動創(chuàng)建一個 Markdown 類實例棍现,重復調(diào)用它的 convert()reset() 函數(shù)。

md = markdown.Markdown()
html1 = md.convert(text1)
md.reset()
html2 = md.convert(text2)
html3 = md.reset().convert(text3)

Markdown 類的構(gòu)造函數(shù)參數(shù)與 markdown 函數(shù)相同镜遣。

擴展說明

1. abbr擴展

from markdown.extensions.abbr import AbbrExtension

語法例子:

The HTML specification
is maintained by the W3C.

*[HTML]: Hyper Text Markup Language
*[W3C]:  World Wide Web Consortium

轉(zhuǎn)換為:

<p>The <abbr title="Hyper Text Markup Language">HTML</abbr> specification
is maintained by the <abbr title="World Wide Web Consortium">W3C</abbr>.</p>

2. attr_list擴展

在 HTML 元素上指定屬性名和屬性值己肮。

from markdown.extensions.abbr import AbbrExtension

基本語法:

{: #someid .someclass somekey='some value' }

例子1:

{: #id1 .class1 id=id2 class="class2 class3" .class4 }

轉(zhuǎn)為

id="id2" class="class2 class3 class4"

注:.id1 被后面的 id=id2 覆蓋,.class1 被后面的 class=class2 class3 覆蓋悲关。

例子2:段落屬性

This is a paragraph.
{: #an_id .a_class }

轉(zhuǎn)為

<p id="an_id" class="a_class">This is a paragraph.</p>

例子3:標題屬性

A setext style header {: #setext}
=================================

### A hash style header ### {: #hash }

轉(zhuǎn)為

<h1 id="setext">A setext style header</h1>
<h3 id="hash">A hash style header</h3>

例子4:鏈接屬性

[link](http://example.com){: class="foo bar" title="Some title!" }

轉(zhuǎn)為

<p><a  class="foo bar" title="Some title!">link</a></p>

3. def_list 擴展

from markdown.extensions.def_list import DefListExtension

語法:

Apple
:   Pomaceous fruit of plants of the genus Malus in
    the family Rosaceae.

Orange
:   The fruit of an evergreen tree of the genus Citrus

轉(zhuǎn)為

<dl>
<dt>Apple</dt>
<dd>Pomaceous fruit of plants of the genus Malus in
the family Rosaceae.</dd>

<dt>Orange</dt>
<dd>The fruit of an evergreen tree of the genus Citrus.</dd>
</dl>

4. fenced_code 擴展

from markdown.extensions.fenced_code import FencedCodeExtension

語法例子:

```python
# python code
```

轉(zhuǎn)為

<pre><code class="python"># python code
</code></pre>

注意:代碼塊只作為文檔的根元素谎僻,不能嵌入列表或引用等塊元素中。

5. footnotes 擴展

from markdown.extensions.footnotes import FootnoteExtension

語法例子:

Footnotes[^1] have a label[^@#$%] and the footnote's content.

[^1]: This is a footnote content.
[^@#$%]: A footnote on the label: "@#$%".

腳注標記必須以 ^ 開始坚洽,后面可包含任意字符(支持空格)戈稿。

腳注注釋可以包含多行內(nèi)容,例如:

[^1]:
    The first paragraph of the definition.

    Paragraph two of the definition.

    > A blockquote with
    > multiple lines.

        a code block

    A final paragraph.

6. tables 擴展

from markdown.extensions.tables import TableExtension

7. admonition 擴展

提供醒目或注意段落讶舰。

from markdown.extensions.admonition import AdmonitionExtension

語法:

!!! type "optional explicit title within double quotes"
    Any number of other indented markdown elements.

    This is the second paragraph.

例子1:

!!! note
    You should note that the title will be automatically capitalized.

轉(zhuǎn)為:

<div class="admonition note">
<p class="admonition-title">Note</p>
<p>You should note that the title will be automatically capitalized.</p>
</div>

例子2:

!!! danger "Don't try this at home"
    ...

轉(zhuǎn)為:

<div class="admonition danger">
<p class="admonition-title">Don't try this at home</p>
<p>...</p>
</div>

8. nl2br 擴展

例子:

>>> import markdown
>>> text = """
... Line 1
... Line 2
... """
>>> html = markdown.markdown(text, extensions=['nl2br'])
>>> print html
<p>Line 1<br />
Line 2</p>

9. mdx_math 擴展

支持 MathJax 數(shù)學公式鞍盗。

安裝:

pip install python-markdown-math

使用:

import markdown
from mdx_math import MathExtension
md = markdown.Markdown(extensions=[MathExtension(enable_dollar_delimiter=True)])
md.convert('$e^x$')
# 輸出 '<p>\n<script type="math/tex">e^x</script>\n</p>'

另外還要在生成的 HTML 的 head 內(nèi)加入:

<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML' async>
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市跳昼,隨后出現(xiàn)的幾起案子般甲,更是在濱河造成了極大的恐慌,老刑警劉巖鹅颊,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件敷存,死亡現(xiàn)場離奇詭異,居然都是意外死亡堪伍,警方通過查閱死者的電腦和手機锚烦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來帝雇,“玉大人涮俄,你說我怎么就攤上這事∈ⅲ” “怎么了彻亲?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵孕锄,是天一觀的道長。 經(jīng)常有香客問我苞尝,道長畸肆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任宙址,我火速辦了婚禮轴脐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘曼氛。我一直安慰自己豁辉,他們只是感情好,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布舀患。 她就那樣靜靜地躺著徽级,像睡著了一般。 火紅的嫁衣襯著肌膚如雪聊浅。 梳的紋絲不亂的頭發(fā)上餐抢,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音低匙,去河邊找鬼旷痕。 笑死,一個胖子當著我的面吹牛顽冶,可吹牛的內(nèi)容都是我干的欺抗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼强重,長吁一口氣:“原來是場噩夢啊……” “哼绞呈!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起间景,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤佃声,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后倘要,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體圾亏,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年封拧,在試婚紗的時候發(fā)現(xiàn)自己被綠了志鹃。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡泽西,死狀恐怖曹铃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情尝苇,我是刑警寧澤铛只,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站糠溜,受9級特大地震影響淳玩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜非竿,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一蜕着、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧红柱,春花似錦承匣、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至零聚,卻和暖如春袍暴,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背隶症。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工政模, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蚂会。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓淋样,卻偏偏與公主長得像,于是被迫代替她去往敵國和親胁住。 傳聞我的和親對象是個殘疾皇子趁猴,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 這是16年5月份編輯的一份比較雜亂適合自己觀看的學習記錄文檔,今天18年5月份再次想寫文章措嵌,發(fā)現(xiàn)簡書還為我保存起的...
    Jenaral閱讀 2,756評論 2 9
  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,381評論 0 5
  • 概要 64學時 3.5學分 章節(jié)安排 電子商務網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,197評論 0 3
  • 蒼白的臉色夾雜沒有定色的發(fā)絲在這個冷凍的季節(jié)一天天的游離著躲叼。 激越的日子總是被習慣的安靜代替。 就像在這個看似很忙...
    潤鍄閱讀 397評論 0 1
  • 人生在世企巢,能有一些非常喜歡并認同的偶像是一件幸運的事情枫慷。在正確思考并踐行這方面,我的偶像是雷.達里奧浪规。他創(chuàng)建的橋水...
    溫勇賢007閱讀 7,891評論 0 2