python转为html_Python下将Markdown转为HTML

本文详细介绍了如何使用Python的Markdown库将Markdown文本转换为HTML。内容包括基本转换方法、扩展的使用,如abbr、attr_list、def_list、fenced_code、footnotes、tables、admonition和nl2br等,并提供了多个示例。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值