Python下将Markdown转为HTML
2019-02-15 本文已影响15人
文均
用 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
函数还可设置以下参数:
-
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
转换为:
<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>