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

如何从LangGraph状态中获取并统计各级章节标题?

解决方法

针对你需要统计一级、二级、三级标题数量的需求,可以通过正则表达式根据各级标题的格式特征精准匹配,下面是具体实现:

标题格式特征分析

  • 一级标题:以**Section [数字]:开头,被Markdown加粗标记包裹
  • 二级标题:以[数字].[数字] 开头,编号包含1个小数点
  • 三级标题:以[数字].[数字].[数字] 开头,编号包含2个小数点

Python代码实现

import re

# 模拟你的edited_outline文本内容
edited_outline_text = """Here is the refined report outline:

**Section 1: Introduction to Management**

1.1 Definition of Management and its significance in planning
1.1.1 Importance of Management in the landscape
1.2 Brief overview of the importance of Management for middle-aged working adults

**Section 2: Types of Challenges Faced by Middle-Aged Working Adults**

2.1 Housing challenges and their impact on stability
2.1.1 Case studies of middle-aged working adults struggling with housing payments
2.2 Credit challenges and their effects on credit scores
2.2.1 Statistics on credit challenges
2.3 Personal financial challenges and their implications on freedom
2.3.1 Examples of personal financial traps and how to avoid them
2.4 Business challenges and their risks for entrepreneurs
2.4.1 Case studies of entrepreneurs struggling with business financial issues
2.5 Tax challenges and their impact on planning
2.5.1 Importance of tax planning in Management
"""

# 匹配一级标题:匹配**Section X: 开头的行
level1_pattern = re.compile(r'^\*\*Section \d+:.*\*\*$', re.MULTILINE)
level1_count = len(level1_pattern.findall(edited_outline_text))

# 匹配二级标题:以X.X 开头,且不是三级标题(避免误匹配)
level2_pattern = re.compile(r'^\d+\.\d+(?!\.\d+) .*$', re.MULTILINE)
level2_count = len(level2_pattern.findall(edited_outline_text))

# 匹配三级标题:以X.X.X 开头的行
level3_pattern = re.compile(r'^\d+\.\d+\.\d+ .*$', re.MULTILINE)
level3_count = len(level3_pattern.findall(edited_outline_text))

print(f"一级标题数量: {level1_count}")
print(f"二级标题数量: {level2_count}")
print(f"三级标题数量: {level3_count}")

代码说明

  • re.MULTILINE 让正则的^和$匹配每行的开头和结尾
  • 二级标题的正则用了(?!\.\d+)负向预查,确保不会把三级标题的前缀误判为二级标题
  • 运行后会输出:
    一级标题数量: 2
    二级标题数量: 7
    三级标题数量: 6
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 10:28:24