#!/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 = [ '', '', '', '', ] for zh_pattern, var_count in templates: placeholder = build_translation_template(var_count) lines.append( f'