# -*- coding: utf-8 -*- """解析两份 COS4:元素树 + 每元素属性集合 + 出现次数""" import zipfile, json, os, re import xml.etree.ElementTree as ET from collections import defaultdict, OrderedDict BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILES = [ r"C:\Users\MZ\Desktop\1易达导出骨架.cos4", r"C:\Users\MZ\Desktop\广联达导出最新架子.COS4", ] OUT = os.path.join(BASE, "两份COS4_结构.json") def decode_name(n): try: return n.encode("cp437").decode("gbk") except Exception: return n def parse_xml(data): """返回 (元素->属性次数, 元素->子元素集合, 元素->出现次数)""" root = ET.fromstring(data) attrs = defaultdict(lambda: defaultdict(int)) children = defaultdict(set) count = defaultdict(int) def walk(e, parent=None): tag = e.tag.split("}")[-1] count[tag] += 1 if parent: children[parent].add(tag) for k, v in e.attrib.items(): attrs[tag][k.split("}")[-1]] += 1 for c in list(e): walk(c, tag) walk(root) return root.tag, attrs, children, count summary = {} for f in FILES: key = os.path.basename(f) z = zipfile.ZipFile(f) names = [(n, decode_name(n)) for n in z.namelist()] proj = [n for n, d in names if d.lower().endswith("project.xml")] units = [(n, d) for n, d in names if not d.lower().endswith("project.xml") and d.lower().endswith(".xml")] ent = {"file": f, "project_xml": proj, "unit_count": len(units)} if proj: data = z.read(proj[0]) root, attrs, children, count = parse_xml(data) ent["root"] = root ent["attrs"] = {k: dict(v) for k, v in attrs.items()} ent["children"] = {k: sorted(v) for k, v in children.items()} ent["count"] = dict(count) # 单位工程:取一个最大的作为样本 + 汇总所有 u_attrs = defaultdict(lambda: defaultdict(int)) u_children = defaultdict(set) u_count = defaultdict(int) roots = set() for n, d in units: try: r, a, c, cnt = parse_xml(z.read(n)) except Exception as e: continue roots.add(r) for k, v in a.items(): for ak, ac in v.items(): u_attrs[k][ak] = max(u_attrs[k][ak], ac) for k, v in c.items(): u_children[k] |= v for k, v in cnt.items(): u_count[k] += v ent["unit_roots"] = sorted(roots) ent["unit_attrs"] = {k: dict(v) for k, v in u_attrs.items()} ent["unit_children"] = {k: sorted(v) for k, v in u_children.items()} ent["unit_count"] = dict(u_count) summary[key] = ent json.dump(summary, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=1) for k, e in summary.items(): print("=" * 70) print(k, "root:", e.get("root"), "units:", e.get("unit_count"), e.get("unit_roots")) print(" 项目文件元素数:", len(e.get("attrs", {})), " 单位工程元素数:", len(e.get("unit_attrs", {}))) print(" 项目属性总数:", sum(len(v) for v in e.get("attrs", {}).values())) print(" 单位工程属性总数:", sum(len(v) for v in e.get("unit_attrs", {}).values())) print(" 项目元素:", sorted(e.get("count", {}).keys())) print("->", OUT)