Python markitdown
最后修改于 2025 年 2 月 24 日
在本文中,我们将展示如何在 Python 中使用 markitdown
库。markitdown
库是一个轻量级的 Markdown 解析器和渲染器,可将 Markdown 文本转换为 HTML。它特别适用于从 Markdown 文件或字符串生成 HTML 内容。
markitdown
库易于使用,并提供了一个简单的 API 来解析和渲染 Markdown。
Markdown 是一种轻量级的标记语言,具有纯文本格式的语法。它设计得易于阅读和编写,允许您将纯文本转换为结构化的 HTML。您可以使用它来格式化文本、创建列表、添加链接、插入图像等。
$ pip install markitdown
在使用 markitdown
库之前,您需要使用 pip
安装它。
markitdown 的基本用法
以下示例演示了如何使用 markitdown
库通过内联字符串将 Markdown 文本转换为 HTML。
import markdown # Markdown text as an inline string markdown_text = """ # Heading 1 ## Heading 2 ### Heading 3 - List item 1 - List item 2 - List item 3 **Bold text** and *italic text*. [Visit ZetCode](https://zetcode.cn) """ # Convert Markdown to HTML html_output = markdown.markdown(markdown_text) print(html_output)
在此程序中,markdown.markdown
函数用于将 Markdown 文本转换为 HTML。生成的 HTML 将打印到控制台。
从文件读取 Markdown
以下示例演示了如何使用 markitdown
库从文件读取 Markdown 并将其转换为 HTML。
# Example Markdown File This is a sample Markdown file. - Item 1 - Item 2 - Item 3 **Bold text** and *italic text*.
这是 example2.md
文件。
import markdown # Read Markdown from a file with open("example.md", "r") as fd: markdown_text = fd.read() # Convert Markdown to HTML html_output = markdown.markdown(markdown_text) print(html_output)
在此程序中,Markdown 内容从名为 example.md
的文件读取,并使用 markdown.markdown
函数转换为 HTML。
自定义 HTML 输出
此示例演示了如何使用自定义扩展来修改使用 markdown
库转换 Markdown 时生成的 HTML。
# Custom Styled Heading This is a sample Markdown file with custom styles. - Item A - Item B - Item C
这是 example3.md
文件。
from markdown.treeprocessors import Treeprocessor from markdown.extensions import Extension class CustomStyleProcessor(Treeprocessor): def run(self, root): for elem in root.iter(): if elem.tag == "h1": elem.set("class", "custom-heading") elif elem.tag == "li": elem.set("class", "custom-item") class CustomStyleExtension(Extension): def extendMarkdown(self, md): md.treeprocessors.register(CustomStyleProcessor(md), "custom_style", 10)
CustomStyleProcessor
是一个自定义 Markdown 树处理器,可在输出之前修改生成的 HTML。它遍历解析后的 Markdown 元素,并将自定义 CSS 类应用于特定的 HTML 标签。
import markdown from custom_renderer import CustomStyleExtension # Read Markdown from a file with open("example_custom.md", "r", encoding="utf-8") as fd: markdown_text = fd.read() # Convert Markdown to HTML with a custom extension html_output = markdown.markdown( markdown_text, extensions=[CustomStyleExtension()] ) print(html_output)
此程序应用了一个自定义扩展,该扩展为标题和列表项添加了 CSS 类,以便于在 HTML 输出中进行样式设置。
处理扩展
以下示例演示了如何使用 markitdown
库的扩展,通过读取文件中的 Markdown 来添加表格和代码块等附加功能。
# Example with Extensions | Column 1 | Column 2 | |----------|----------| | Row 1 | Data 1 | | Row 2 | Data 2 | ```python print("Hello there!") ```
这是 example4.md
文件。
import markdown # Read Markdown from a file with open("example4.md", "r", encoding="utf-8") as fd: markdown_text = fd.read() # Convert Markdown to HTML with correct extensions html_output = markdown.markdown( markdown_text, extensions=["tables", "fenced_code"] ) print(html_output)
在此程序中,使用 tables
和 fenced_code
来启用 Markdown 文本中的表格和代码块渲染。
将 HTML 转换为 Markdown
convert
函数将给定的 HTML 代码转换为 Markdown。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>Document title</h1> <p> A simple HTML document. </p> </body> </html>
这是一个简单的 HTML 文档。
from markitdown import MarkItDown converter = MarkItDown() filename = 'index.html' # Convert HTML to Markdown mk_content = converter.convert(filename) print(mk_content.text_content)
该示例利用 convert
函数将一个 HTML 页面转换为 Markdown。
$ py main.py # Document title A simple HTML document.
输出仅包含核心元素。
为了获得完整的 HTML 文档,我们需要自己创建它。
import argparse import markdown parser = argparse.ArgumentParser(description="Convert a Markdown file to HTML.") parser.add_argument("filename", help="The name of the Markdown file to convert") # Parse arguments args = parser.parse_args() mk_file = args.filename # Read Markdown from the file provided as an argument with open(mk_file, "r", encoding="utf-8") as fd: markdown_text = fd.read() # Convert Markdown to HTML body_content = markdown.markdown(markdown_text, tab_length=4) # Create the full HTML structure html_output = f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> {body_content} </body> </html>""" print(html_output)
该程序读取作为 CLI 选项给出的文件名内容,将其转换为 HTML,并使用 Python fstring 将其与整个文档结构合并。
使用 LLM
在以下示例中,我们使用 Llama 视觉模型获取图像的描述。我们使用 Groq 服务。
import os from markitdown import MarkItDown from groq import Groq client = Groq( api_key=os.environ.get("GROQ_API_KEY"), ) mid = MarkItDown(llm_client=client, llm_model="llama-3.2-11b-vision-preview") result = mid.convert("character.png") print(result.text_content)
llama-3.2-11b-vision-preview
模型具有多模态(视觉)能力,这意味着它可以处理图像输入和文本。
result = mid.convert("character.png")
我们将图像文件名传递给 convert
方法。
来源
在本文中,我们展示了如何在 Python 中使用 markitdown
库进行 Markdown 解析和渲染。markitdown
库是从 Markdown 文本生成 HTML 内容的强大工具。
作者
列出所有 Python 教程。