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
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...