Python Markdown解析利器----mistune詳細用法記錄

来源:https://www.cnblogs.com/lueye/archive/2022/09/30/16745836.html
-Advertisement-
Play Games

1、無論是淺拷貝還是深拷貝,拷貝對象後是否會開闢新記憶體,取決於被拷貝對象的數據類型是否可變,一般來講,可變的數據類型會開闢新記憶體,不可變數據類型反之不會開闢新記憶體,進行記憶體地址的引用(-5-256以外的大整數池會開闢記憶體,但我本地進行測試比較記憶體還是一樣的,有問題) 2、要在單層、嵌套型對象中逐一比 ...


@

目錄

小試牛刀

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 ↩︎


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Java基礎之變數 1.變數概述 1.1 為什麼需要變數 不論是使用哪種高級語言編寫程式,變數都是其程式的基本組成單位。變數有三個基本要素:類型、名稱、值。 class Test{ public static void main(String []args){ int a = 1;//定義一個變數, ...
  • time庫的使用:Python中內置了一些與時間處理相關的庫,如time、datatime和calendar庫。 其中time庫是Python中處理時間的標準庫,是最基礎的時間處理庫。 time庫的功能如下: (1)電腦時間的表達 (2)提供獲取系統時間並格式化輸出功能 (3)提供系統級精確計時功 ...
  • csv的簡單介紹 CSV (Comma Separated Values),即逗號分隔值(也稱字元分隔值,因為分隔符可以不是逗號),是一種常用的文本格式,用以存儲表格數據,包括數字或者字元。很多程式在處理數據時都會碰到csv這種格式的文件。python自帶了csv模塊,專門用於處理csv文件的讀取 ...
  • 1、任務介紹 需求分析 爬取豆瓣電影Top250的基本信息,包括電影的名稱,豆瓣評分,評價數,電影概況,電影鏈接等。 https://movie.douban.com/top250 2、基本流程 2.1、準備工作 通過瀏覽器查看分析目標網頁,學習編程基礎規範 與Java的一些區別,Python沒有主 ...
  • 2022-09-30 F對象: 在shell中是用於兩個有關聯的屬性之間的查詢。 使用實例: 查詢書籍表中閱讀量大於評論量的記錄 前提,進入pycharm,進入虛擬環境,進入shell環境。 首先,要使用F對象,那麼就需要導入F對象 from django.db.models import F 後進 ...
  • 介紹了分散式鎖的特性,模擬想要實現redis分散式鎖的演變流程,分析redisson源碼是如何實現分散式鎖的,面對高併發下,我們該如何提升分散式鎖性能 ...
  • 1.冒泡排序(Bubble Sort) | 第0輪 | 3 | 1 | 4 | 1 | 5 | 9 | 2 | 6 | 5 | 3 | 5 | 8 | 9 | | | | | | | | | | | | | | | | | 第1輪 | 1 | 3 | 1 | 4 | 5 | 2 | 6 | 5 | ...
  • 前言 tkinter:GUI桌面應用開發模塊,寫軟體界面你還可以打包成exe軟體, 哪怕你沒有python環境, 一樣可以用雖然不一定要有界面, 但是有界面, 用戶體驗很棒… 環境使用 Python 3.8 Pycharm 模塊使用 import tkinter import webbrowser ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...