import re import os from xml.dom import minidom # 配置区域: PATTERN = "\{=\w+\}.+" # 转换值的正则表达式 TARGET_ATTRS = ("name", "text") # 目标的类型 OUTDIR_NAME = "output" # 输出文件夹的名称 # 下面都是代码 OUTDIR = os.sep.join([os.path.dirname(__file__), OUTDIR_NAME]) BASE_ATTRS = (('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'), ('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'), ('xsi:schemaLocation', 'https://www.w3schools.com/xml ../../../../../../resources/language.xsd'), ('type', 'string')) os.chdir(os.path.dirname(__file__)) if not os.path.exists(OUTDIR): os.mkdir(OUTDIR) assert os.path.isdir(OUTDIR), f"{OUTDIR} 不是文件夹" def mk_result_dom(): dom = minidom.Document() base = dom.createElement("base") tags = dom.createElement("tags") tag = dom.createElement("tag") strings = dom.createElement("strings") dom.appendChild(base) base.appendChild(tags) base.appendChild(strings) tags.appendChild(tag) for k, v in BASE_ATTRS: base.setAttribute(k, v) tag.setAttribute("language", "简体中文") return dom def scan_string(node, strings): """对节点的 name 和 text 属性进行扫描并添加到 strings 中""" count = 0 if not hasattr(node, "getAttribute"): return count for attr in TARGET_ATTRS: val = node.getAttribute(attr) if re.fullmatch(PATTERN, val): count += 1 string = strings.ownerDocument.createElement("string") end_idx = val.find("}") string.setAttribute("id", val[2:end_idx]) string.setAttribute("text", val[end_idx + 1 :]) strings.appendChild(string) return count def convert(dom, strings): """遍历每个节点 dom 被处理的文件 strings 输出文件的 strings 节点 """ count = 0 for child in dom.childNodes: count += scan_string(child, strings) if child.hasChildNodes(): count += convert(child, strings) return count def read_and_convert(fpath, outdir): """读取 fpath 的文件并输出同名文件到 outdir""" try: encoding = "utf-8" dom = minidom.parse(open(fpath, encoding=encoding)) except UnicodeDecodeError: encoding = "gbk" dom = minidom.parse(open(fpath, encoding=encoding)) out_dom = mk_result_dom() count = convert(dom, out_dom.getElementsByTagName("strings")[0]) out_path = os.sep.join([outdir, os.path.basename(fpath)]) with open(out_path, "w", encoding=encoding) as f_obj: out_dom.writexml(f_obj, encoding='UTF-8', indent='\n', addindent=' ') print("发现", count, "个匹配属性, 结果已写入到", out_path) def main(): while True: path = input(">> 输入文件路径\n>> ") if os.path.isfile(path): targets = [path] else: targets = [os.sep.join([path, fname]) for fname in os.listdir(path)] for target in targets: try: if target.upper()[-4:] == ".XML": read_and_convert(target, OUTDIR) except Exception as e: print(target, "处理错误", repr(e)) if __name__ == "__main__": main()