kgrag/app_pkg/examples/md_header_convert.py
2026-06-30 13:35:52 +08:00

48 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
def convert_numbered_headings(text):
"""
将编号转换为对应的Markdown标题
- `1.2` → `## 1.2`
- `1.2.1` → `### 1.2.1`
- `1. 3. 1` → `### 1.3.1`(去掉空格)
"""
# 替换全角 `` 为半角 `.`
text = text.replace('', '.')
# 遍历每一行,处理标题
lines = text.split('\n')
for i in range(len(lines)):
line = lines[i].strip()
if not line:
continue
# 只匹配 `1.2` 或 `1.2.1` 形式的编号,允许 `1. 3. 1` 这种格式
match = re.match(r'^(#*\s*)(\d+(?:\s*\.\s*\d+)+)', line)
if match:
prefix, num = match.groups()
level = num.count('.') # `.` 的个数决定层级
new_prefix = '#' * (level + 1) # 1.2 → ##, 1.2.1 → ###
# 去掉数字和 `.` 之间的空格
clean_num = re.sub(r'\s*\.\s*', '.', num)
# 替换标题
lines[i] = f"{new_prefix} {clean_num}{line[match.end():]}"
return '\n'.join(lines)
# # 示例文本
# text = """
# # 1资料与方法
# 11一般资料选取2019年12月至2021年1月焦煤集团中央医院收治的60例...
# # 12选取标准
# 121纳入标准(1)经CT、MI检查确诊为颅内动脉狭窄...
# """
# print(convert_numbered_headings(text))