草庐IT

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

一切皆对象 2023-04-19 原文

@

目录

小试牛刀

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/
[链接](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)

上述代码你跑成功了吗?是不是还有许多不解的地方?没关系下面有你想要的

开始使用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文本转义,如:[1]
plugins 启用的插件功能 None 导入插件后添加到plugins中启用插件,他的传入值为列表,如:[2]
hard_wrap 将每一新行分成<br> False 启用后md文件中的每一行都会解析成单独一行
renderer 默认选项有AST解析器mistune.AstRenderer()和HTML解析器mistune.HTMLRenderer() , 也可以自定义[3]

mistune中插件

插件使用方法(以 删除线(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) from mistune.plugins import plugin_strikethrough
2 注脚(footnotes) from mistune.plugins import plugin_footnotes
3 表格(table) from mistune.plugins import plugin_table
4 链接(url) from mistune.plugins import plugin_url
5 任务列表(task_lists) from mistune.plugins import plugin_task_lists
6 描述列表(def_list) from mistune.plugins import plugin_def_list
7 缩写(abbr) from mistune.plugins import plugin_abbr

删除线(strikethrough)

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

注脚(footnotes)

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

content in paragraph with footnote[4] markup.

表格(table)

语法:
简易式表格 :
Simple formatted table:
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell
复杂的表格:
Complex formatted table:
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
表格对齐
Align formatted table:
简易写法
Left Header | Center Header | Right Header
:----------- | :-------------: | ------------:
Conent Cell | Content Cell | Content Cell
复杂写法
| Left Header | Center Header | Right Header |
| :---------- | :-------------: | ------------: |
| Conent Cell | Content Cell | Content Cell |
显示:
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell

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

链接(url)

语法

允许使用默认的链接创建url
For instance, https://typlog.com/
显示:

For instance , https://typlog.com/

任务列表

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

描述列表

语法
First term
: First definition
: Second definition

Second term
: Third definition
显示:

First term
First definition
Second definition
Second term
Third definition

缩写(abber)

语法
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 '<span class="math">' + escape(text) + '</span>'
        return '<code>' + escape(text) + '</code>'

# 使用自定义解析器
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 '<pre><code>' + mistune.escape(code) + '</code></pre>'

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):
    # ``inline`` is ``md.inline``, see below
    # "m"是匹配的正则表达式项 ``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'<a href="{link}">{title}</a>'

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])

资源

名称 链接
官方说明 https://mistune.readthedocs.io/en/v2.0.4/guide.html
mistune GitHub主页 https://github.com/lepture/mistune
mistune 作者写的其他插件 https://github.com/lepture/mistune-contrib

  1. markdown('<div>hello</div>') 返回 '<div>hello</div>' ↩︎

  2. markdown = mistune.create_markdown(plugins=['strikethrough']) # 启用删除线插件 ↩︎

  3. renderer = mistune.HTMLRenderer() markdown = mistune.create_markdown(renderer) ↩︎

  4. footnote explain ↩︎

有关Python Markdown解析利器----mistune详细用法记录的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  5. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  6. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

  7. 在VMware16虚拟机安装Ubuntu详细教程 - 2

    在VMware16.2.4安装Ubuntu一、安装VMware1.打开VMwareWorkstationPro官网,点击即可进入。2.进入后向下滑动找到Workstation16ProforWindows,点击立即下载。3.下载完成,文件大小615MB,如下图:4.鼠标右击,以管理员身份运行。5.点击下一步6.勾选条款,点击下一步7.先勾选,再点击下一步8.去掉勾选,点击下一步9.点击下一步10.点击安装11.点击许可证12.在百度上搜索VM16许可证,复制填入,然后点击输入即可,亲测有效。13.点击完成14.重启系统,点击是15.双击VMwareWorkstationPro图标,进入虚拟机主

  8. ruby-on-rails - 事件记录 : Select max of limit - 2

    我正在尝试将以下SQL查询转换为ActiveRecord,它正在融化我的大脑。deletefromtablewhereid有什么想法吗?我想做的是限制表中的行数。所以,我想删除少于最近10个条目的所有内容。编辑:通过结合以下几个答案找到了解决方案。Temperature.where('id这给我留下了最新的10个条目。 最佳答案 从您的SQL来看,您似乎想要从表中删除前10条记录。我相信到目前为止的大多数答案都会如此。这里有两个额外的选择:基于MurifoX的版本:Table.where(:id=>Table.order(:id).

  9. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  10. Ruby 守护进程导致 ActiveRecord 记录器 IOError - 2

    我目前正在用Ruby编写一个项目,它使用ActiveRecordgem进行数据库交互,我正在尝试使用ActiveRecord::Base.logger记录所有数据库事件具有以下代码的属性ActiveRecord::Base.logger=Logger.new(File.open('logs/database.log','a'))这适用于迁移等(出于某种原因似乎需要启用日志记录,因为它在禁用时会出现NilClass错误)但是当我尝试运行包含调用ActiveRecord对象的线程守护程序的项目时脚本失败并出现以下错误/System/Library/Frameworks/Ruby.frame

随机推荐