| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 读取 outputs/db_error_keys.md 第二章"含变量提示清单"表格,
- 生成 I18n/Templates.xml 的正则模板条目。
- 用法:
- python scripts/md_to_templates.py
- 输出默认写入 I18n/Templates.xml(可通过 -o 指定)。
- """
- import argparse
- import re
- import os
- from xml.sax.saxutils import escape
- def escape_attr(value: str) -> str:
- return escape(value, {'"': """})
- def parse_markdown_table(md_path: str):
- """解析 markdown 表格,返回 (zh_pattern, var_count) 列表。"""
- with open(md_path, "r", encoding="utf-8") as f:
- lines = f.readlines()
- templates = []
- in_table = False
- header_seen = False
- for line in lines:
- stripped = line.strip()
- if stripped.startswith("|") and "原始中文模板" in stripped:
- in_table = True
- header_seen = True
- continue
- if in_table:
- if not stripped.startswith("|"):
- break
- if re.match(r"\|\s*[-:]+\s*\|", stripped):
- continue
- cols = [c.strip() for c in stripped.strip("|").split("|")]
- if len(cols) >= 2:
- zh_template = cols[1]
- # 统计变量个数
- var_count = len(re.findall(r"\{[0-9]+\}", zh_template))
- if var_count > 0 and "{0}" in zh_template:
- # 把 {x} 替换为 (.*?)
- zh_pattern = re.sub(r"\{[0-9]+\}", r"(.*?)", zh_template)
- templates.append((zh_pattern, var_count))
- return templates
- def build_translation_template(var_count: int):
- """生成占位符翻译模板(后续需人工替换为真实翻译)。"""
- return "".join("{" + str(i) + "}" for i in range(var_count))
- def main():
- parser = argparse.ArgumentParser(description="从 db_error_keys.md 生成 Templates.xml")
- parser.add_argument("-i", "--input", default="outputs/db_error_keys.md", help="输入 markdown 文件")
- parser.add_argument("-o", "--output", default="I18n/Templates.xml", help="输出 XML 文件")
- args = parser.parse_args()
- if not os.path.exists(args.input):
- print(f"[ERROR] Input file not found: {args.input}")
- return
- templates = parse_markdown_table(args.input)
- if not templates:
- print("[WARN] No templates found in the markdown table.")
- return
- lines = [
- '<?xml version="1.0" encoding="utf-8"?>',
- '<!-- 由 scripts/md_to_templates.py 从 outputs/db_error_keys.md 自动生成 -->',
- '<!-- 请把 en/vi/id 属性中的占位符替换为真实翻译 -->',
- '<Templates>',
- ]
- for zh_pattern, var_count in templates:
- placeholder = build_translation_template(var_count)
- lines.append(
- f' <Template zh="{escape_attr(zh_pattern)}"'
- f' en="{escape_attr(placeholder)}"'
- f' vi="{escape_attr(placeholder)}"'
- f' id="{escape_attr(placeholder)}"/>'
- )
- lines.append("</Templates>")
- with open(args.output, "w", encoding="utf-8") as f:
- f.write("\n".join(lines))
- print(f"Generated {len(templates)} templates -> {args.output}")
- if __name__ == "__main__":
- main()
|