import re import os import time from xml.dom.minidom import parse, Text # 配置区域: PATTERN = "\{=\w+\}\w+" # 转换值的正则表达式 TARGET_TAG = "name" # 目标的类型, 如果是要处理 节点就改成 "text" TARGET_ATTR = "name" # 要处理的属性, 只有当节点只有一个属性才进行处理 REP_TAG = "string" # 替换为哪种节点 OUTDIR_NAME = "output" # 输出文件夹的名称 # 下面都是代码 OUTDIR = os.sep.join([os.path.dirname(__file__), OUTDIR_NAME]) os.chdir(os.path.dirname(__file__)) if not os.path.exists(OUTDIR): os.mkdir(OUTDIR) assert os.path.isdir(OUTDIR), f"{OUTDIR} 不是文件夹" def is_target(node): """判断节点是否是需要替换的节点""" attributes = node.attributes if attributes is None: return False items = attributes.items() return all( ( node.tagName == TARGET_TAG, len(items) == 1, items[0][0] == TARGET_ATTR, (re.fullmatch(PATTERN, items[0][1]) is not None), ) ) def replace(node): """对符合要求的节点进行处理""" val = node.getAttribute(TARGET_ATTR) end_idx = val.find("}") node.tagName = REP_TAG node.setAttribute("id", val[2:end_idx]) node.setAttribute("text", val[end_idx + 1 :]) node.removeAttribute("name") def convert(dom): """遍历每个节点""" for child in dom.childNodes: if isinstance(child, Text): continue if child.hasChildNodes(): convert(child) else: if is_target(child): replace(child) def read_and_convert(fpath, outdir): """读取 fpath 的文件并输出同名文件到 outdir""" print("开始读取", fpath) try: encoding = "utf-8" dom = parse(open(fpath, encoding=encoding)) except UnicodeDecodeError: encoding = "gbk" dom = parse(open(fpath, encoding=encoding)) print("开始转换", fpath) convert(dom) out_path = os.sep.join([outdir, os.path.basename(fpath)]) with open(out_path, "w", encoding=encoding) as f_obj: f_obj.write(dom.toxml()) print("转换后文件已写入到", out_path) def main(): 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: if target.upper()[-4:] == ".XML": read_and_convert(target, OUTDIR) print("十秒后将自动关闭") time.sleep(10) if __name__ == "__main__": main()