You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python基于Markdown标题层级生成带有序编号的目录

实现思路

你只需要维护两个计数器分别记录一级、二级标题的序号即可,核心逻辑如下:

  1. 初始化一级标题计数为0,每次识别到一级标题就计数+1,同时重置二级标题计数为0
  2. 识别到二级标题时,在当前一级标题序号的基础上对二级标题计数+1
  3. 非标题行直接跳过不处理

完整可运行代码

# 输入的原始Markdown文本
input_md = """
# Algorithms
This chapter covers the most basic algorithms.
## Sorting
Quicksort is fast and widely used in practice
Merge sort is a deterministic algorithm
## Searching
DFS and BFS are widely used graph searching algorithms
# Data Structures
more text
## more data structures
"""

def generate_markdown_toc(md_content):
    h1_counter = 0
    h2_counter = 0
    toc_lines = []
    # 逐行遍历文本
    for line in md_content.splitlines():
        stripped_line = line.strip()
        # 匹配一级标题(注意#后加空格,避免误匹配###等多级标题、代码里的#注释)
        if stripped_line.startswith('# '):
            h1_counter += 1
            h2_counter = 0
            # 提取#后面的标题内容
            title_content = stripped_line[2:].strip()
            toc_lines.append(f"{h1_counter}. {title_content}")
        # 匹配二级标题
        elif stripped_line.startswith('## '):
            h2_counter += 1
            title_content = stripped_line[3:].strip()
            toc_lines.append(f"{h1_counter}.{h2_counter}. {title_content}")
    return '\n'.join(toc_lines)

# 输出结果
print(generate_markdown_toc(input_md))

运行输出

1. Algorithms
1.1. Sorting
1.2. Searching
2. Data Structures
2.1. more data structures

如果需要和你给出的示例格式完全对齐,只需要修改二级标题拼接的字符串格式即可,后续要支持三级、四级标题的话,新增对应层级的计数器和判断规则就行。

内容的提问来源于stack exchange,提问作者moth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:09:00