markdown 是一种轻量级标记语言,用于以纯文本形式编写格式化文档。
它使用简洁的符号表示标题、列表、表格、链接、代码块等结构,易于阅读与编辑,同时可通过渲染生成 html、pdf、幻灯片等格式。
markdown 广泛应用于技术文档、博客、github readme、笔记管理以及学术写作等场景。
一、markdown 格式特点
markdown 文件扩展名通常为 .md 或 .markdown。
主要特点:
(1)纯文本
文件内容可直接在任何文本编辑器中查看。
(2)可读性强
即使不渲染,也能理解文档结构。
(3)轻量化标记
使用符号表示格式,如 # 表示标题,* 或 - 表示列表。
(4)可扩展
支持表格、脚注、数学公式(需扩展)、代码高亮等。
(5)跨平台
兼容 git、博客平台、文档生成器等。
示例 markdown 内容:
# 学生成绩表| id | name | score ||----|-------|-------|| 1 | alice | 95 || 2 | bob | 88 || 3 | carol | 90 |- 高分学生:成绩 >= 90- 平均分:91.0> 注:markdown 文件支持引用、列表、表格及代码块。
该示例展示了 markdown 的基本语法:标题、表格、列表与引用。
二、在 python 中表示 markdown 数据
(1)使用字符串与内存文件对象
当我们想在内存中操作 markdown,而不立即写入磁盘时,可使用 io.stringio。
from io import stringio md_text = """# 学生成绩表 | id | name | score ||----|-------|-------|| 1 | alice | 95 || 2 | bob | 88 || 3 | carol | 90 |""" # 创建内存中文本文件对象buf = stringio(md_text)print(buf.read())
stringio 适合测试、临时存储或处理网络请求中的 markdown 内容。
(2)使用列表/字典在内存中表示表格数据
在生成 markdown 表格前,通常先在内存中准备数据:
students = [ {"id": 1, "name": "alice", "score": 95}, {"id": 2, "name": "bob", "score": 88}, {"id": 3, "name": "carol", "score": 90},]这种结构便于程序化生成 markdown 表格或列表。
三、使用 python 标准库生成 markdown
虽然 python 标准库没有专门的 markdown 模块,但可以直接通过字符串操作生成 markdown 文件。
(1)生成 markdown 表格
students = [ {"id": 1, "name": "alice", "score": 95}, {"id": 2, "name": "bob", "score": 88}, {"id": 3, "name": "carol", "score": 90},]
# 表
头md_lines = ["| id | name | score |", "|----|------|-------|"]
# 添加每一行
for s in students: md_lines.append(f"| {s['id']} | {s['name']} | {s['score']} |")
# 写入 markdown 文件
with open("students.md", "w", encoding="utf-8") as f: f.write("\n".join(md_lines))
print("students.md 文件已保存。")输出 markdown 文件内容:
| id | name | score ||----|------|-------|| 1 | alice | 95 || 2 | bob | 88 || 3 | carol | 90 |
(2)生成标题、列表与代码块
students = [ {"id": 1, "name": "alice", "score": 95}, {"id": 2, "name": "bob", "score": 88}, {"id": 3, "name": "carol", "score": 90},]
md_lines = []
# 标题
md_lines.append("# 学生成绩分析")
# 列表
top_students = [s for s in students if s["score"] >= 90]md_lines.append("- 高分学生:")for s in top_students: md_lines.append(f" - {s['name']}:{s['score']}")
# 代码块
md_lines.append("\n```python")md_lines.append("print('hello, markdown!')")md_lines.append("```")
# 写入文件
with open("analysis.md", "w", encoding="utf-8") as f: f.write("\n".join(md_lines))
print("analysis.md 文件已保存。")生成文件可直接渲染为带列表和代码块的 markdown 文档。
四、使用第三方库处理 markdown
(1)将 markdown 转换为 html
import markdown
with open("students.md", "r", encoding="utf-8") as f: md_content = f.read()
html_content = markdown.markdown(md_content)
# 保存 html 文件
with open("students.html", "w", encoding="utf-8") as f: f.write(html_content)
print("students.html 已生成,可在浏览器中查看。")说明:markdown 库支持表格、代码块、标题和列表渲染为 html,方便展示。
(2)使用 pandas 直接生成 markdown 表格
import pandas as pd
df = pd.dataframe(students)
# 生成 markdown 表格md_table = df.to_markdown(index=false)print(md_table)
# 保存到文件with open("students_table.md", "w", encoding="utf-8") as f: f.write(md_table)输出示例:
| id | name | score ||------|-------|---------|| 1 | alice | 95 || 2 | bob | 88 || 3 | carol | 90 |
pandas to_markdown 方法可快速将 dataframe 输出为 markdown 表格。
(3)案例:markdown 文件生成与分析
以下示例展示从内存数据 → markdown 表格 → html 渲染 → 保存文件的完整流程。
import pandas as pdimport markdown
# 构造原始数据
students = [ {"id": 1, "name": "alice", "score": 95}, {"id": 2, "name": "bob", "score": 88}, {"id": 3, "name": "carol", "score": 90}, {"id": 4, "name": "david", "score": 70},]
df = pd.dataframe(students)
# 筛选高分学生
top_students = df[df["score"] >= 90]
# 生成 markdown 表格
md_lines = ["# 高分学生表", top_students.to_markdown(index=false)]with open("top_students.md", "w", encoding="utf-8") as f: f.write("\n".join(md_lines))
# 渲染为 html
with open("top_students.md", "r", encoding="utf-8") as f: md_content = f.read()
html_content = markdown.markdown(md_content)with open("top_students.html", "w", encoding="utf-8") as f: f.write(html_content)
print("top_students.md 与 top_students.html 已生成。")markdown 文件内容示例:
# 高分学生表| id | name | score ||------|-------|---------|| 1 | alice | 95 || 3 | carol | 90 |
五、解析 markdown 文件并提取内容
在某些场景下,我们需要读取并解析 markdown 内容,将标题、列表、表格或代码块转换为 python 数据结构,以便进一步分析。
(1)使用 markdown + beautifulsoup 提取 html 内容
import markdownfrom bs4 import beautifulsoup
# 读取 markdown 文件
with open("top_students.md", "r", encoding="utf-8") as f: md_content = f.read()
# 渲染为 html
html_content = markdown.markdown(md_content)
# 使用 beautifulsoup 解析 html
soup = beautifulsoup(html_content, "html.parser")
# 提取标题
title = soup.find(["h1", "h2", "h3"])print("标题:", title.text)
# 提取表格
table = soup.find("table")rows = []for tr in table.find_all("tr"): cells = [td.get_text(strip=true) for td in tr.find_all(["th", "td"])] rows.append(cells)
print("表格内容:")for r in rows: print(r)输出示例:
标题: 高分学生表表格内容:['id', 'name', 'score']['1', 'alice', '95']['3', 'carol', '90']
(2)使用正则表达式(re 标准库)提取表格内容
import re
with open("top_students.md", "r", encoding="utf-8") as f: md_content = f.read()
# 匹配 markdown 表格行
lines = md_content.splitlines()table_rows = []
for line in lines: if "|" in line and not re.match(r"^\s*#|^-{2,}", line): cells = [cell.strip() for cell in line.strip("|").split("|")] table_rows.append(cells)
print("解析表格:")for row in table_rows: print(row)说明:
正则方法适合简单表格,但不支持嵌套或复杂 markdown 结构。
对于多级列表、代码块或引用,推荐 html 渲染 + beautifulsoup 方法。
(3)案例:markdown 表格 → python 数据 → 数据分析
import pandas as pdimport markdownfrom bs4 import beautifulsoup
# 读取 markdown 并渲染为 html
with open("top_students.md", "r", encoding="utf-8") as f: md_content = f.read()
html_content = markdown.markdown(md_content)soup = beautifulsoup(html_content, "html.parser")
# 提取表格数据
table = soup.find("table")rows = []for tr in table.find_all("tr"): cells = [td.get_text(strip=true) for td in tr.find_all(["th", "td"])] rows.append(cells)
# 转换为 dataframe
df = pd.dataframe(rows[1:], columns=rows[0])df["score"] = df["score"].astype(int)
# 统计平均分
avg_score = df["score"].mean()print(df)print(f"平均分:{avg_score:.1f}")运行结果:
id name score0 1 alice 951 3 carol 90平均分:92.5
小结
markdown 是轻量级、可读性强、跨平台的文档格式。python 标准库通过字符串操作即可生成 markdown 文件。
第三方库 markdown 可将 markdown 渲染为 html,方便展示和解析。pandas to_markdown 方法可快速生成 markdown 表格。
综合流程包括:生成 markdown → 渲染/解析 → 转换数据结构 → 数据分析 → 输出结果,适合文档化与数据处理相结合的场景。
到此这篇关于python操作markdown格式文件的全攻略的文章就介绍到这了,更多相关python操作markdown文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论