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

6.5. Python之markdown模块

Python-Markdown是John Gruber的Markdown语法的python实现。但是与一般Markdown还是有些许差别。这些差别包括:

  • Python-Markdown默认忽略掉单词中间的加重标识(middle-word emphasis)。如some_long_filename.txt不会被转译成somelongfilename.txt

  • Markdown语法规则中指出如果一个列表组件包含多个段落,那么后面的段落必须空出4个空格或者一个tab。与其他语法解释器不同,Python-Markdown严格遵守这条规定,并且所有在列表中的块一级元素都如此规定。

  • 当列表的一行遇到其他列表标识(如星号,数字等),官方规则没有指明是否需要另起一行。为了一致性,Python-Markdown也不做修改。但是Sane List 这个扩展模块提供了更友好的解决方式。

另外,Python-Markdown还提供的弹性的扩展机制。允许使用者在不修改项目源代码的情况下,对自己想要扩展的语法进行扩展开发。 官方已经提供的扩展模块如下:

Extension    “Name”
Extra    extra
Abbreviations    abbr
Attribute Lists    attr_list
Definition Lists  def_list
Fenced Code Blocks  fenced_code
Footnotes    footnotes
Tables    tables
Smart Strong    smart_strong
Admonition    admonition
CodeHilite    codehilite
HeaderId    headerid
Meta-Data    meta
New Line to Break    nl2br
Sane Lists    sane_lists
SmartyPants    smarty
Table of Contents    toc
WikiLinks    wikilinks

安装

pip3 install markdown

将markdown转换成html

>>> import markdown
>>> text = "Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。"
>>> html = markdown.markdown(text)
>>> html
'<p>Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。</p>'

工作中要处理转换就写个函数:

def txt2html(text):
    return markdown.markdown(text)

之后就直接用函数转换:

abc = txt2html(abc)