import re from pathlib import Path path = Path(__file__).resolve().parents[1] / "doc" / "企微客户服务-功能实现说明.md" s = path.read_text(encoding="utf-8") CHAPTER_CN = {1: "四", 2: "五", 3: "六", 4: "七", 5: "八", 6: "九", 7: "十", 8: "十一", 9: "十二", 10: "十三", 11: "十四"} def slug_title(title: str) -> str: t = title.strip().lower() t = re.sub(r"[「」『』""''()()、,。!?::;;·]", "", t) t = re.sub(r"\s+", "-", t) t = re.sub(r"-+", "-", t).strip("-") return t # Fix module chapter headers (all were incorrectly collapsed to 四) for mod in range(1, 12): ch = CHAPTER_CN[mod] s = re.sub( rf"^## 四、模块 {mod}:", f"## {ch}、模块 {mod}:", s, count=1, flags=re.M, ) # Build anchor map from ### headers anchors: dict[str, str] = {} for m in re.finditer(r"^### (\d+)\.(\d+) (.+)$", s, re.M): ch, sec, title = m.group(1), m.group(2), m.group(3) key = f"{ch}.{sec}" anchors[key] = f"#{ch}{sec}-{slug_title(title)}" def fix_toc_link(m: re.Match) -> str: ch, sec = m.group(1), m.group(2) key = f"{ch}.{sec}" if key not in anchors: return m.group(0) return f"[§{ch}.{sec}]({anchors[key]})" s = re.sub(r"\[§(\d+)\.(\d+)\]\(#[^)]+\)", fix_toc_link, s) # Intro cleanup s = s.replace( "为开发人员补充:**每条功能的详细实现流程**、**需实现的 QiWe 官方接口**(对照已爬取官方文档)、**项目需产出的文档清单**。", "为开发人员补充:**每条功能的详细实现流程**、**需实现的 QiWe 官方接口**(对照已爬取官方文档)。", ) path.write_text(s, encoding="utf-8") print("fixed", path, "anchors", len(anchors))