>>> from env_helper import info; info()
页面更新时间: 2024-01-17 15:57:40
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-17-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

6.2. Python之markdown模块

我在我的项目中,为了编辑和维护方便使用的是MD来编辑(数据库和文档都是MD),但是实际展示中生成的API中,需要HTML标签来展示,故此这里需要一个能转换的工具来帮忙。

在 Python 中可以用来处理 Markdown 语句的模块包括: markdown , markdown2 , snudown 。 不同的库对于语法处理或扩展功能会稍有区别。 如果没有特殊要求,建议使用 markdown 模块。

6.2.1. 安装:

通过 pip 安装:

pip install markdown

在 Debian / Ubuntu 中安装:

sudo apt install -y python3-markdown

6.2.2. 使用:

>>> text = '''
>>> # Title 1
>>>
>>> contents.
>>>
>>> line1,
>>> line2.
>>>
>>> The line is for `code` .
>>>
>>> ## Title 2
>>>
>>> ending...
>>> '''
>>>
>>> import markdown
>>> html = markdown.markdown(text)
>>> print(html)
<h1>Title 1</h1>
<p>contents.</p>
<p>line1,<br />
line2.</p>
<p>The line is for <code>code</code> .</p>
<h2>Title 2</h2>
<p>ending...</p>

6.2.3. 支持

由于有些扩展需要手动打开
>>> markdown.markdown(text, extensions=['markdown.extensions.extra'])
'<h1>Title 1</h1>n<p>contents.</p>n<p>line1,<br />nline2.</p>n<p>The line is for <code>code</code> .</p>n<h2>Title 2</h2>n<p>ending...</p>'

6.2.4. 代码高亮

>>> markdown.markdown(text, extensions=['markdown.extensions.codehilite'])
'<h1>Title 1</h1>n<p>contents.</p>n<p>line1,<br />nline2.</p>n<p>The line is for <code>code</code> .</p>n<h2>Title 2</h2>n<p>ending...</p>'

6.2.5. 表格处理

>>> markdown.markdown(text, extensions=['markdown.extensions.tables'])
'<h1>Title 1</h1>n<p>contents.</p>n<p>line1,<br />nline2.</p>n<p>The line is for <code>code</code> .</p>n<h2>Title 2</h2>n<p>ending...</p>'

6.2.6. 预处理

进入由md转为html前进行的处理,过滤或修改一些语法规则或纠正错误比如‘—’个中划线应该是‘* * * ’ 的错误。

>>> from markdown.preprocessors import Preprocessor
>>> class MyPreprocessor(Preprocessor):
>>>     pass