python把文本转换为html_Python下将Markdown转为HTML

用 markdown 包进行转换。

pip install Markdown

基本用法

使用 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 函数还可设置以下参数:

output_format: 参数默认值为 xhtml,可改为 html5。

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

转换为:

The HTML specification

is maintained by the W3C.

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 }

转为

This is a paragraph.

例子3:标题属性

A setext style header {: #setext}

=================================

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

转为

A setext style header

A hash style header

例子4:链接属性

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

转为

link

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

转为

Apple
Pomaceous fruit of plants of the genus Malus in

the family Rosaceae.

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

4. fenced_code 扩展

from markdown.extensions.fenced_code import FencedCodeExtension

语法例子:

```python

# python code

```

转为

# python code

注意:代码块只作为文档的根元素,不能嵌入列表或引用等块元素中。

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.

转为:

Note

You should note that the title will be automatically capitalized.

例子2:

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

...

转为:

Don't try this at home

...

8. nl2br 扩展

例子:

>>> import markdown

>>> text = """

... Line 1

... Line 2

... """

>>> html = markdown.markdown(text, extensions=['nl2br'])

>>> print html

Line 1

Line 2

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$')

# 输出 '

\n\n

'

另外还要在生成的 HTML 的 head 内加入:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值