md_to_templates.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 读取 outputs/db_error_keys.md 第二章"含变量提示清单"表格,
  5. 生成 I18n/Templates.xml 的正则模板条目。
  6. 用法:
  7. python scripts/md_to_templates.py
  8. 输出默认写入 I18n/Templates.xml(可通过 -o 指定)。
  9. """
  10. import argparse
  11. import re
  12. import os
  13. from xml.sax.saxutils import escape
  14. def escape_attr(value: str) -> str:
  15. return escape(value, {'"': """})
  16. def parse_markdown_table(md_path: str):
  17. """解析 markdown 表格,返回 (zh_pattern, var_count) 列表。"""
  18. with open(md_path, "r", encoding="utf-8") as f:
  19. lines = f.readlines()
  20. templates = []
  21. in_table = False
  22. header_seen = False
  23. for line in lines:
  24. stripped = line.strip()
  25. if stripped.startswith("|") and "原始中文模板" in stripped:
  26. in_table = True
  27. header_seen = True
  28. continue
  29. if in_table:
  30. if not stripped.startswith("|"):
  31. break
  32. if re.match(r"\|\s*[-:]+\s*\|", stripped):
  33. continue
  34. cols = [c.strip() for c in stripped.strip("|").split("|")]
  35. if len(cols) >= 2:
  36. zh_template = cols[1]
  37. # 统计变量个数
  38. var_count = len(re.findall(r"\{[0-9]+\}", zh_template))
  39. if var_count > 0 and "{0}" in zh_template:
  40. # 把 {x} 替换为 (.*?)
  41. zh_pattern = re.sub(r"\{[0-9]+\}", r"(.*?)", zh_template)
  42. templates.append((zh_pattern, var_count))
  43. return templates
  44. def build_translation_template(var_count: int):
  45. """生成占位符翻译模板(后续需人工替换为真实翻译)。"""
  46. return "".join("{" + str(i) + "}" for i in range(var_count))
  47. def main():
  48. parser = argparse.ArgumentParser(description="从 db_error_keys.md 生成 Templates.xml")
  49. parser.add_argument("-i", "--input", default="outputs/db_error_keys.md", help="输入 markdown 文件")
  50. parser.add_argument("-o", "--output", default="I18n/Templates.xml", help="输出 XML 文件")
  51. args = parser.parse_args()
  52. if not os.path.exists(args.input):
  53. print(f"[ERROR] Input file not found: {args.input}")
  54. return
  55. templates = parse_markdown_table(args.input)
  56. if not templates:
  57. print("[WARN] No templates found in the markdown table.")
  58. return
  59. lines = [
  60. '<?xml version="1.0" encoding="utf-8"?>',
  61. '<!-- 由 scripts/md_to_templates.py 从 outputs/db_error_keys.md 自动生成 -->',
  62. '<!-- 请把 en/vi/id 属性中的占位符替换为真实翻译 -->',
  63. '<Templates>',
  64. ]
  65. for zh_pattern, var_count in templates:
  66. placeholder = build_translation_template(var_count)
  67. lines.append(
  68. f' <Template zh="{escape_attr(zh_pattern)}"'
  69. f' en="{escape_attr(placeholder)}"'
  70. f' vi="{escape_attr(placeholder)}"'
  71. f' id="{escape_attr(placeholder)}"/>'
  72. )
  73. lines.append("</Templates>")
  74. with open(args.output, "w", encoding="utf-8") as f:
  75. f.write("\n".join(lines))
  76. print(f"Generated {len(templates)} templates -> {args.output}")
  77. if __name__ == "__main__":
  78. main()