Files
pricing_review/_analysis/scripts/collect_attrs.py

42 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""收集一个目录下所有 XML 的 元素->属性名集合(只读)。
输出 JSON:{element: {attr: [出现的文件数, 出现次数]}}
"""
import sys, os, json, collections
import xml.etree.ElementTree as ET
def walk(path):
result = collections.defaultdict(collections.Counter) # elem -> attr -> count
files = collections.defaultdict(set) # elem -> set(files)
nfiles = 0
for root, _dirs, names in os.walk(path):
for n in names:
if not n.lower().endswith(".xml"):
continue
fp = os.path.join(root, n)
nfiles += 1
try:
for _ev, el in ET.iterparse(fp, events=("end",)):
tag = el.tag
if not isinstance(tag, str):
continue
for a in el.attrib:
result[tag][a] += 1
files[tag].add(n)
el.clear()
except Exception as e:
print("ERR", fp, e, file=sys.stderr)
out = {}
for tag, attrs in result.items():
out[tag] = {
"_files": len(files[tag]),
"attrs": {a: c for a, c in sorted(attrs.items())},
}
print(json.dumps({"dir": path, "xml_files": nfiles, "elements": out},
ensure_ascii=False, indent=1))
if __name__ == "__main__":
walk(sys.argv[1])