Python下将Markdown转为HTML

markdown 包进行转换。

pip install Markdown

参考文档:https://python-markdown.github.io/

基本用法

使用 markdown.markdown() 函数将 markdown 字符串转换为 html 字符串。

import codecs, markdown

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

# 转为 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() 函数的参数 extensions 指定扩展列表。

扩展列表的每一项为扩展类实例或扩展名(无参数扩展):

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

在构造扩展实例时可对扩展进行配置:

from markdown.extensions import Extension

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

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

其他参数和用法

markdown.markdown 函数还可设置以下参数:

  1. output_format: 参数默认值为 xhtml,可改为 html5
  2. tab_length: 源文件中tab字符代表的空格数,默认值为4。

每次调用 markdown.markdwon 函数时,都创建了一个 markdown.Markdown 类实例。当处理大量文件时,为提高效率,可手动创建一个 Markdown 类实例,重复调用它的 convert()reset() 函数。

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

Markdown 类的构造函数参数与 markdown 函数相同。

扩展说明

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

转换为:

<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 }

转为

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

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

例子2:段落属性

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

转为

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

例子3:标题属性

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

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

转为

<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!" }

转为

<p><a href="http://example.com" 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

转为

<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
```

转为

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

脚注标记必须以 ^ 开始,后面可包含任意字符(支持空格)。

脚注注释可以包含多行内容,例如:

[^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.

转为:

<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"
    ...

转为:

<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 数学公式。

安装:

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 内加入:

<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML' async>
</script>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,642评论 2 9
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,313评论 0 5
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 8,629评论 0 3
  • 苍白的脸色夹杂没有定色的发丝在这个冷冻的季节一天天的游离着。 激越的日子总是被习惯的安静代替。 就像在这个看似很忙...
    润鍄阅读 379评论 0 1
  • 人生在世,能有一些非常喜欢并认同的偶像是一件幸运的事情。在正确思考并践行这方面,我的偶像是雷.达里奥。他创建的桥水...
    温勇贤007阅读 7,813评论 0 2