Markdown 目录生成器
从Markdown标题生成带锚链接的目录。
常见问题
代码实现
import re
def heading_to_anchor(text: str) -> str:
"""Convert heading text to a GitHub-Flavored Markdown anchor."""
anchor = text.lower()
anchor = re.sub(r"[^\w\s-]", "", anchor) # remove punctuation (keep letters, digits, -, _)
anchor = re.sub(r"\s+", "-", anchor.strip()) # spaces → hyphens
return anchor
def generate_toc(markdown: str, max_depth: int = 3, bullet: str = "-") -> str:
lines = []
seen: dict[str, int] = {}
for line in markdown.splitlines():
m = re.match(r"^(#{1,6})\s+(.*)", line)
if not m:
continue
level = len(m.group(1))
if level > max_depth:
continue
title = m.group(2).strip()
anchor = heading_to_anchor(title)
# Deduplicate: second occurrence → anchor-1, third → anchor-2, ...
count = seen.get(anchor, 0)
seen[anchor] = count + 1
if count > 0:
anchor = f"{anchor}-{count}"
indent = " " * (level - 1)
lines.append(f"{indent}{bullet} [{title}](#{anchor})")
return "\n".join(lines)
md = """# Getting Started
## Installation
### Prerequisites
### Install
## Configuration
## Usage
# Advanced
## Performance
## Security
"""
print(generate_toc(md, max_depth=3, bullet="-"))
# - [Getting Started](#getting-started)
# - [Installation](#installation)
# - [Prerequisites](#prerequisites)
# - [Install](#install)
# - [Configuration](#configuration)
# - [Usage](#usage)
# - [Advanced](#advanced)
# - [Performance](#performance)
# - [Security](#security)Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.