renumber_impl_doc.py 1.7 KB

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