用 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。</