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
  • 一、openKylin簡介 openKylin(開放麒麟) 社區是在開源、自願、平等和協作的基礎上,由基礎軟硬體企業、非營利性組織、社團組織、高等院校、科研機構和個人開發者共同創立的一個開源社區,致力於通過開源、開放的社區合作,構建桌面操作系統開源社區,推動Linux開源技術及其軟硬體生態繁榮發展。 ...
  • 簡介 Flurl是一個用於構建基於HTTP請求的C#代碼的庫。它的主要目的是簡化和優雅地處理網路請求(只用很少的代碼完成請求)。Flurl提供了一種簡單的方法來構建GET、POST、PUT等類型的請求,以及處理響應和異常。它還提供了一些高級功能,如鏈式調用、緩存請求結果、自動重定向等。本文將介紹Fl ...
  • 一:背景 1. 講故事 最近也挺奇怪,看到了兩起 CPU 爆高的案例,且誘因也是一致的,覺得有一些代表性,合併分享出來幫助大家來避坑吧,閑話不多說,直接上 windbg 分析。 二:WinDbg 分析 1. CPU 真的爆高嗎 這裡要提醒一下,別人說爆高不一定真的就是爆高,我們一定要拿數據說話,可以 ...
  • 剛開始寫文章,封裝Base基類的時候,添加了trycatch異常塊,不過當時沒有去記錄日誌,直接return了。有小伙伴勸我不要吃了Exception 其實沒有啦,項目剛開始,我覺得先做好整體結構比較好。像是蓋樓一樣。先把樓體建造出來,然後再一步一步的美化完善。 基礎的倉儲模式已經ok,Autofa ...
  • 框架目標 什麼是框架,框架能做到什麼? 把一個方向的技術研發做封裝,具備通用性,讓使用框架的開發者用起來很輕鬆。 屬性: 通用性 健壯性 穩定性 擴展性 高性能 組件化 跨平臺 從零開始-搭建框架 建立項目 主鍵查詢功能開發 綁定實體 一步一步的給大家推導: 一邊寫一邊測試 從零開始--搭建框架 1 ...
  • 大家好,我是沙漠盡頭的狼。 本方首發於Dotnet9,介紹使用dnSpy調試第三方.NET庫源碼,行文目錄: 安裝dnSpy 編寫示常式序 調試示常式序 調試.NET庫原生方法 總結 1. 安裝dnSpy dnSpy是一款功能強大的.NET程式反編譯工具,可以對.NET程式進行反編譯,代替庫文檔的功 ...
  • 在`Windows`操作系統中,每個進程的虛擬地址空間都被劃分為若幹記憶體塊,每個記憶體塊都具有一些屬性,如記憶體大小、保護模式、類型等。這些屬性可以通過`VirtualQueryEx`函數查詢得到。該函數可用於查詢進程虛擬地址空間中的記憶體信息的函數。它的作用類似於`Windows`操作系統中的`Task... ...
  • 背景介紹 1,最近有一個大數據量插入的操作入庫的業務場景,需要先做一些其他修改操作,然後在執行插入操作,由於插入數據可能會很多,用到多線程去拆分數據並行處理來提高響應時間,如果有一個線程執行失敗,則全部回滾。 2,在spring中可以使用@Transactional註解去控制事務,使出現異常時會進行 ...
  • 線程(thread)是操作系統能夠進行運算調度的最小單位。它被包含在進程之中,是進程中的實際 運作單位。一條線程指的是進程中一個單一順序的控制流,一個進程中可以併發多個線程,每條線 程並行執行不同的任務。 ...
  • 發現Java 21的StringBuilder和StringBuffer中多了repeat方法: /** * @throws IllegalArgumentException {@inheritDoc} * * @since 21 */ @Override public StringBuilder ...