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资料与方法 # 1.1一般资料选取2019年12月至2021年1月焦煤集团中央医院收治的60例... # # 1.2选取标准 # 1.2.1纳入标准(1)经CT、MRI检查确诊为颅内动脉狭窄... # """ # print(convert_numbered_headings(text))