为了编辑和维护使用,用MD来编辑(数据库和文档都是MD),但是实际展示中生成的API中,需要HTML标签来展示,故此这里需要一个能转换的工具来帮忙。
在 Python 中可以用来处理 Markdown 语句的模块包括: markdown , markdown2 , snudown 。 不同的库对于语法处理或扩展功能会稍有区别。 如果没有特殊要求,建议使用 markdown 模块。
通过 pip 安装:
# pip install markdown
在 Debian / Ubuntu 中安装:
sudo apt install -y python3-markdown
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>
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>'
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>'
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>'
from markdown.preprocessors import Preprocessor
class MyPreprocessor(Preprocessor):
pass