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

markdown 包進(jìn)行轉(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 編碼。

使用擴(kuò)展

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

擴(kuò)展列表的每一項(xiàng)為擴(kuò)展類實(shí)例或擴(kuò)展名(無參數(shù)擴(kuò)展):

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

在構(gòu)造擴(kuò)展實(shí)例時可對擴(kuò)展進(jìn)行配置:

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è)置以下參數(shù):

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

每次調(diào)用 markdown.markdwon 函數(shù)時,都創(chuàng)建了一個 markdown.Markdown 類實(shí)例。當(dāng)處理大量文件時,為提高效率,可手動創(chuàng)建一個 Markdown 類實(shí)例,重復(fù)調(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ù)相同。

擴(kuò)展說明

1. abbr擴(kuò)展

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擴(kuò)展

在 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:標(biāo)題屬性

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 擴(kuò)展

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 擴(kuò)展

from markdown.extensions.fenced_code import FencedCodeExtension

語法例子:

```python
# python code
```

轉(zhuǎn)為

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

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

5. footnotes 擴(kuò)展

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: "@#$%".

腳注標(biāo)記必須以 ^ 開始,后面可包含任意字符(支持空格)。

腳注注釋可以包含多行內(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 擴(kuò)展

from markdown.extensions.tables import TableExtension

7. admonition 擴(kuò)展

提供醒目或注意段落。

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 擴(kuò)展

例子:

>>> 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 擴(kuò)展

支持 MathJax 數(shù)學(xué)公式。

安裝:

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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容