Python Markdown解析利器—-mistune详细用法记录

import mistune
from mistune.directives import DirectiveToc,DirectiveInclude
from mistune.plugins import plugin_footnotes,\
plugin_strikethrough,plugin_table,plugin_url,\
plugin_task_lists,plugin_def_list,plugin_abbr

renderer = mistune.HTMLRenderer()
markdown = mistune.create_markdown(renderer,escape=False,plugins=[DirectiveToc(),
                                               DirectiveInclude(),# toc支持
                                               plugin_footnotes, # 注脚
                                               plugin_strikethrough, # 删除线
                                               plugin_table, # 表格
                                               plugin_url, # 链接
                                               plugin_task_lists , # 任务列表
                                               plugin_def_list, # 自定义列表
                                               plugin_abbr, # 缩写
                                               ]
                            )
mdText = '''

@[toc]
H1 title
~~here is the content~~

https://typlog.com/
[链接](https://typlog.com/)

content in paragraph with footnote[^1] markup.

[^1]: footnote explain

## H2 title

- [x] item 1
- [ ] item 2

First term
: First definition
: Second definition

Second term
: Third definition

H1 title

The HTML specification is maintained by the W3C.

*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium

.. include:: study.md

'''

md_HTML = markdown(mdText)

with open("a.html","w+",encoding="utf-8") as f:
    f.write(md_HTML)

Python Markdown解析利器----mistune详细用法记录

mistune简单使用

import mistune

mistune.html(YOUR_MARKDOWN_TEXT)

mistune高级用法(自定义mistune)

import mistune

markdown = mistune.create_markdown()
markdown('YOUR_MARKDOWN_TEXT')

参数 释义 默认值 备注 escape HTML转义 TRUE 默认情况下将html文本转义,如:

plugins 启用的插件功能 None 导入插件后添加到plugins中启用插件,他的传入值为列表,如:

hard_wrap 将每一新行分成

False 启用后md文件中的每一行都会解析成单独一行 renderer 默认选项有AST解析器mistune.AstRenderer()和HTML解析器mistune.HTMLRenderer() , 也可以自定义

插件使用方法(以 删除线(strikethrough) 为例)

mistune.html() 默认支持strikethrough. 创建自己的markdown实例:

markdown = mistune.create_markdown(plugins=['strikethrough'])

其他创建你自己的markdown实例的方法:

from mistune.plugins import plugin_strikethrough

renderer = mistune.HTMLRenderer()
markdown = mistune.Markdown(renderer, plugins=[plugin_strikethrough])

插件包名

内置插件

序号 插件目录 引用 1. 删除线(strikethrough)

2 注脚(footnotes)

3 表格(table)

4 链接(url)

5 任务列表(task_lists)

6 描述列表(def_list)

7 缩写(abbr)

语法:
~~here is the content~~
显示:
here is the content

语法: content in paragraph with footnote[^1] markup. [^1]: footnote explain
显示:

content in paragraph with footnote [4] markup.

语法:
简易式表格 :
Simple formatted table:
First Header | Second Header
Content Cell | Content Cell
Content Cell | Content Cell

Left Header Center Header Right Header Conent Cell Content Cell Content Cell

语法
- [x] item 1
- [ ] item 2
显示:

  • item 1
  • item 2

语法
First term
: First definition
: Second definition
Second term
: Third definition
显示:

First term First definition Second definition Second term Third definition

语法
The HTML specification is maintained by the W3C.

[HTML]: Hyper Text Markup Language
[W3C]: World Wide Web Consortium
显示:

The HTML specification is maintained by the W3C.

使用解析器

你可以使用自己的渲染器来自定义HTML的输出.创建一个mistune.HTMLRenderer的子类:

import mistune
from mistune import escape
class MyRenderer(mistune.HTMLRenderer):
    def codespan(self, text):
        if text.startswith('$') and text.endswith('$'):
            return '' + escape(text) + ''
        return '' + escape(text) + ''

使用自定义解析器
markdown = mistune.create_markdown(renderer=MyRenderer())
print(markdown('hi $a^2=4$'))

可用的解析器功能列表

1.内联级 inline level text(self, text) link(self, link, text=None, title=None) image(self, src, alt=””, title=None) emphasis(self, text) strong(self, text) codespan(self, text) linebreak(self) newline(self) inline_html(self, html) 2.块级 block level paragraph(self, text) heading(self, text, level) heading(self, text, level, tid) # when TOC directive is enabled thematic_break(self) block_text(self, text) block_code(self, code, info=None) block_quote(self, text) block_html(self, html) block_error(self, html) list(self, text, ordered, level, start=None) list_item(self, text, level) 3.由删除插件提供 provided by strikethrough plugin strikethrough(self, text) 4.由表格插件提供 provide by table plugin table(self, text) table_head(self, text) table_body(self, text) table_row(self, text) table_cell(self, text, align=None, is_head=False) 5.由注胶插件提供 provided by footnotes plugin footnote_ref(self, key, index) footnotes(self, text) footnote_item(self, text, key, index) 6.确定最终呈现内容(定义输出) Finalize rendered content (define output) finalize(self, data)

自定义渲染器

Midtune 支持开发者自定义渲染器功能,例如,创建一个代码高亮渲染器

import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html

class HighlightRenderer(mistune.HTMLRenderer):
    def block_code(self, code, lang=None):
        if lang:
            lexer = get_lexer_by_name(lang, stripall=True)
            formatter = html.HtmlFormatter()
            return highlight(code, lexer, formatter)
        return '' + mistune.escape(code) + ''

markdown = mistune.create_markdown(renderer=HighlightRenderer())

print(markdown('python\nassert 1 == 1\n'))

Mistune有一些内置插件,您可以查看Mistune/plugins中的源代码,了解如何编写插件。让我们以GitHub Wiki链接为例:

一个mistune插件示例:

为Wiki链接定义正则表达式 define regex for Wiki links
import mistune
WIKI_PATTERN = (
    r'\[\['                   # [[
    r'([\s\S]+?\|[\s\S]+?)'   # Page 2|Page 2
    r'\]\](?!\])'             # ]]
)

定义如何解析匹配项 define how to parse matched item
def parse_wiki(inline, m, state):
    #  is .inline, see below
    # "m"是匹配的正则表达式项  is matched regex item
    text = m.group(1)
    title, link = text.split('|')
    return 'wiki', link, title

定义如何渲染HTML define how to render HTML
def render_html_wiki(link, title):
    return f'{title}'

def plugin_wiki(md):
    # 这是一个内联语法,因此我们将wiki规则注册到md.inline中
    # this is an inline grammar, so we register wiki rule into md.inline
    # 语法: md.inline.register_rule(name, 正则表达式, 函数[解析匹配项])
    # 注意名字要一直匹配
    md.inline.register_rule('wiki', WIKI_PATTERN, parse_wiki)

    # 将wiki规则添加到活动规则中
    # add wiki rule into active rules
    md.inline.rules.append('wiki')

    # 添加HTML渲染器 add HTML renderer
    if md.renderer.NAME == 'html':
        md.renderer.register('wiki', render_html_wiki)

使用这个插件 use this plugin
markdown = mistune.create_markdown(plugins=[plugin_wiki])

名称 链接 官方说明

mistune GitHub主页

mistune 作者写的其他插件

Original: https://www.cnblogs.com/lueye/p/16745836.html
Author: 盧瞳
Title: Python Markdown解析利器—-mistune详细用法记录

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/809000/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Python_numpy函数入门

    NumPy 数组的维数称为秩(rank),秩就是轴的数量,即数组的维度,一维数组的秩为 1,二维数组的秩为 2,以此类推。 在 NumPy中,每一个线性的数组称为是一个轴(axis…

    Python 2023年5月24日
    055
  • Python搜索书名获取整本资源_笔趣阁

    前言 偶然一天把某项目文档传到手机上,用手机自带的阅读器方便随时拿出来查阅。看着我那好久没点开的阅读器,再看着书架上摆着几本不知道是多久之前导入的小说。闭上眼睛,我仿佛看到了那个时…

    Python 2023年5月24日
    072
  • 利用云服务器发布项目

    平时开发我会写一些小demo,我自己觉得有用的会集中起来形成一个项目,本来想利用gitee的gitee page直接部署出来,但后面了解了下,它只支持官网之类的静态页面,无法与后台…

    Python 2023年10月12日
    031
  • Python – PyPDF2模块的简单使用

    1.简介 PyPDF的前身是PyPDF包在2005年发布,该包的最后一个版本发布于2010年,后来大约经过一年左右,名为Phasit的公司赞助PyPDF的一个分支后来命名为PyPD…

    Python 2023年5月23日
    054
  • Python容器数据类型(列表、元组)

    使用 + 可以将多个列表或者是元组结合成为一个 lst = [1, 2, 3] lst1 = [‘one’, ‘two’, ‘three’] res =lst + lst1 pri…

    Python 2023年11月9日
    037
  • 秒杀微服务实现抢购代金券功能

    文章目录 * – 需求分析 – 秒杀场景的解决方案 – 数据库表设计 – + 代金券表 + 抢购活动表 + 订单表 – …

    Python 2023年10月7日
    029
  • Flask与HTML初探

    Flask是一种web框架,为后续深入学习Django框架做铺垫,需要先使用flask框架了解一下HTML(超文本传输语言) from flask import Flask, re…

    Python 2023年8月14日
    048
  • Pytorch基本数据类型tensor

    文章目录 * – + * 目的 * Python和Pytorch数据类型对应 * 创建tensor的方法 * 一些常用的生成tensor方法 * tensor的切片与索…

    Python 2023年8月29日
    036
  • pandas 实现无关联key数据交叉连接(cross join)

    有两个数据帧,分别有一列col1,col2,他们没有相同的key: left = pd.DataFrame({‘col1’ : [‘A’, ‘B’, ‘C’]}) right = …

    Python 2023年8月7日
    036
  • Python报错ValueError: substring not found

    Contents Overview 1 Lesson 1: Index Concepts 3 Lesson 2: Concepts – Statistics 29 Lesson 3…

    Python 2023年8月9日
    058
  • python与html结合显示本地图片_显示图像通过flask / python从HTML连接到HTML

    要在Python 中实时写入图像 并在HTML 上实时显示 ,可以使用OpenCV和Flask 。下面是一个简单的示例代码: <em>python</em>…

    Python 2023年8月15日
    072
  • 天池数据-耳机情感分析

    import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt i…

    Python 2023年8月22日
    053
  • pandas之groupby函数

    sql中的分组语句group by很重要,pandas中也有类似的分组函数,即groupby,本文就主要介绍下它的用法。 和sql中的分组类似,pandas中的groupby函数也…

    Python 2023年8月21日
    051
  • 02 Python笔记:如何用pygame在python中导入图片

    当前使用python3.8.5 1. 如何加载一张图片: pygame.image.load("images/me_destroy_1.png").conver…

    Python 2023年9月19日
    071
  • python基础⑪-继承与派生

    系列文章目录 python基础①-基础环境搭建和工具使用python基础②-常用的各种数据类型初认知python基础③-数据类型常用的操作和方法字符串、数值、boolpython基…

    Python 2023年9月22日
    031
  • pytorch基础知识

    动态图和静态图的区别?自动微分是什么? 一文详解pytorch的”动态图”与”自动微分”技术 – 知乎 教程 https…

    Python 2023年8月27日
    046
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球