Mercurial > hg > lxmldump
annotate lxmldump.py @ 9:2a8c65d22f86
Moar.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 11 May 2021 09:33:21 +0300 |
parents | ce07bb2a247b |
children | 013f0cd9e5b3 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/python3 -B |
2 # coding=utf-8 | |
3 ### | |
4 | 4 ### lxmldump - Dump ISO/FDIS 1951 XML file data |
5 ### Programmed and designed by Matti 'ccr' Hämäläinen <ccr@tnsp.org> | |
6 ### (C) Copyright 2021 Tecnic Software productions (TNSP) | |
7 ### | |
8 ### Python 3.7+ required! | |
0 | 9 ### |
10 import sys | |
11 import signal | |
12 import re | |
13 from pathlib import Path | |
14 import xml.etree.ElementTree as xmlET | |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
15 import unicodedata |
0 | 16 |
17 assert sys.version_info >= (3, 7) | |
18 | |
19 | |
20 ### | |
21 ### Default settings | |
22 ### | |
23 pkk_cfg = { | |
8 | 24 "verbosity": 3, |
25 | |
26 "annotate": False, | |
0 | 27 "dump": False, |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
28 "normalize": False, |
7 | 29 |
30 "debug": False, | |
0 | 31 } |
32 | |
33 | |
7 | 34 pkk_str_fmap = { |
35 "Fragment" : ["<", ">"], | |
36 } | |
37 | |
38 | |
39 pkk_debug_list = [ | |
40 "ahas", | |
41 "ahavakkaine", | |
42 "ahavakala", | |
43 "ahavakoittuo", | |
44 "ahvaliha", | |
9 | 45 "aloilleh", |
7 | 46 ] |
47 | |
48 | |
0 | 49 ### |
50 ### Misc. helper functions, etc | |
51 ### | |
52 def pkk_cleanup(): | |
53 return 0 | |
54 | |
55 | |
56 ## Wrapper for print() | |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
57 def pkk_print(smsg): |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
58 if pkk_cfg["normalize"]: |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
59 sys.stdout.write(unicodedata.normalize("NFC", smsg)) |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
60 else: |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
61 sys.stdout.write(smsg) |
0 | 62 |
7 | 63 def pkk_printi(indent, smsg): |
64 pkk_print((" " * indent) + smsg) | |
65 | |
0 | 66 |
8 | 67 def pkk_verbosity(lvl): |
68 return pkk_cfg["verbosity"] >= lvl | |
69 | |
70 | |
0 | 71 ## Fatal error handler |
72 def pkk_fatal(smsg): | |
73 print(u"ERROR: "+ smsg) | |
74 sys.exit(1) | |
75 | |
76 | |
77 ## Handler for SIGINT signals | |
78 def pkk_signal_handler(signal, frame): | |
79 pkk_cleanup() | |
80 print(u"\nQuitting due to SIGINT / Ctrl+C!") | |
81 sys.exit(1) | |
82 | |
83 | |
9 | 84 ## |
85 def pkk_ptr_to_text(pnode): | |
86 # return "PTR: <{}>".format("".join(pnode.itertext()).strip()) | |
87 return "PTR: <{}>".format(xmlET.tostring(pnode)) | |
88 | |
89 | |
7 | 90 def pkk_get_text(lnode): |
91 stmp = "" | |
92 for pnode in lnode.iter(): | |
9 | 93 if pnode.tag == "Ptr": |
94 stmp += pkk_ptr_to_text(pnode) | |
95 else: | |
96 if isinstance(pnode.text, str): | |
97 ptext = pnode.text | |
98 if pkk_cfg["annotate"] and isinstance(pnode.tag, str) and pnode.tag in pkk_str_fmap: | |
99 stmp += pkk_str_fmap[pnode.tag][0] + ptext + pkk_str_fmap[pnode.tag][1] | |
100 else: | |
101 stmp += ptext | |
7 | 102 |
9 | 103 if isinstance(pnode.tail, str): |
104 stmp += " "+ pnode.tail.strip() | |
7 | 105 |
106 return stmp.strip() | |
107 | |
108 | |
6 | 109 ## |
7 | 110 def pkk_dump_recursive(indent, lnode): |
111 if lnode.tag in ["Example"]: | |
112 stmp = pkk_get_text(lnode) | |
9 | 113 pkk_printi(indent, "{} \"{}\"\n".format(lnode.tag, stmp)) |
6 | 114 else: |
7 | 115 if isinstance(lnode.text, str): |
116 stmp = lnode.text.strip() | |
117 if stmp != "": | |
118 stmp = " \""+ stmp +"\"" | |
119 else: | |
120 stmp = "" | |
6 | 121 |
122 if len(lnode.attrib) > 0: | |
123 atmp = " "+str(lnode.attrib) | |
124 else: | |
125 atmp = "" | |
126 | |
7 | 127 pkk_printi(indent, "{}{}{}\n".format(lnode.tag, atmp, stmp)) |
6 | 128 for qnode in lnode.findall("./*"): |
7 | 129 pkk_dump_recursive(indent + 1, qnode) |
6 | 130 |
131 | |
132 ## | |
7 | 133 def pkk_output_one(indent, dnode, dsub): |
134 for qnode in dnode.findall(dsub): | |
135 pkk_printi(indent, "{}\n".format(pkk_get_text(qnode))) | |
136 | |
137 def pkk_output_subs(indent, dnode, dsub, dname): | |
138 for qnode in dnode.findall(dsub): | |
139 pkk_printi(indent, "{} \"{}\"\n".format(dname, pkk_get_text(qnode))) | |
140 | |
141 | |
142 def pkk_output_sense(indent, dnode): | |
143 pkk_output_subs(indent, dnode, "./SearchForm", "srch") | |
144 pkk_output_subs(indent, dnode, "./Definition", "defn") | |
145 | |
146 for wnode in dnode.findall("./ExampleBlock/ExampleCtn"): | |
147 sstr = pkk_get_text(wnode.find("./Example")) | |
8 | 148 lstr = "" |
6 | 149 |
8 | 150 if pkk_verbosity(1): |
151 ltmp = [] | |
152 for qnode in wnode.findall("./FreeTopic[@type='levikki']/GeographicalUsage"): | |
153 ltmp.append("{} [{}]".format(pkk_get_text(qnode), qnode.attrib["class"])) | |
154 | |
155 if len(ltmp) > 0: | |
156 lstr = " ({})".format(", ".join(ltmp)) | |
7 | 157 |
158 pkk_printi(indent + 1, "{} \"{}\"{}\n".format("exmp", sstr, lstr)) | |
159 | |
160 | |
161 def pkk_output_node(indent, dnode): | |
6 | 162 |
7 | 163 for wnode in dnode.findall("./HeadwordCtn"): |
164 pkk_output_one (indent, wnode, "./Headword") | |
165 pkk_output_sense(indent + 1, wnode) | |
6 | 166 |
7 | 167 index = 1 |
168 for wnode in dnode.findall("./SenseGrp"): | |
8 | 169 pkk_printi(indent + 1, "sense #{}\n".format(index)) |
7 | 170 pkk_output_sense(indent + 2, wnode) |
171 index += 1 | |
6 | 172 |
173 | |
0 | 174 ### |
175 ### Main program starts | |
176 ### | |
177 signal.signal(signal.SIGINT, pkk_signal_handler) | |
178 | |
179 | |
180 ### Check if we have arguments | |
181 pkk_show_help = False | |
182 pkk_filenames = [] | |
183 argc = 1 | |
184 while argc < len(sys.argv): | |
185 arg = sys.argv[argc] | |
186 | |
187 needs_param = False | |
188 if argc + 1 < len(sys.argv): | |
189 param = sys.argv[argc + 1] | |
190 else: | |
191 param = None | |
192 | |
193 # Check for option type arg | |
194 if arg[0:1] == "-": | |
195 oarg = arg | |
196 arg = arg.lstrip("-") | |
197 | |
198 if arg == "help" or arg == "h": | |
199 pkk_show_help = True | |
200 elif arg == "dump" or arg == "d": | |
201 pkk_cfg["dump"] = True | |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
202 elif arg == "normalize" or arg == "n": |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
203 pkk_cfg["normalize"] = True |
8 | 204 elif arg == "annotate" or arg == "a": |
205 pkk_cfg["annotate"] = True | |
7 | 206 elif arg == "p": |
207 pkk_cfg["debug"] = True | |
8 | 208 elif arg == "verbosity" or arg == "v": |
209 needs_param = True | |
210 pkk_cfg["verbosity"] = param | |
0 | 211 else: |
212 pkk_fatal(u"Invalid option argument '{0}'.".format(oarg)) | |
213 | |
214 if needs_param and param == None: | |
215 pkk_fatal(u"Option '{0}' requires an argument.".format(oarg)) | |
216 else: | |
217 # Non-option argument | |
218 pkk_filenames.append(arg) | |
219 | |
220 if needs_param: | |
221 argc += 2 | |
222 else: | |
223 argc += 1 | |
224 | |
225 | |
226 ### Show help if requested | |
227 if pkk_show_help or len(pkk_filenames) == 0: | |
228 print(u"lxmldump - Dump ISO/FDIS 1951 XML file data") | |
229 print(u"Usage: {0} <options> <input xml file(s)>". | |
230 format(str(Path(sys.argv[0]).name))) | |
231 print(u"") | |
232 print(u" --help Show this help") | |
233 print(u" -d, --dump Dump mode") | |
6 | 234 print(u" -n, --normalize Output NFC normalized Unicode") |
8 | 235 print(u" -a, --annotate Annotate strings") |
236 print(u" -v, --verbosity <n> Set verbosity level (0 - 3)") | |
0 | 237 print(u"") |
238 sys.exit(0) | |
239 | |
240 | |
8 | 241 ### Validate settings |
242 try: | |
243 pkk_cfg["verbosity"] = int(pkk_cfg["verbosity"]) | |
244 except Exception as e: | |
245 pkk_fatal(u"Verbosity level is not a valid integer.") | |
246 if pkk_cfg["verbosity"] < 0 or pkk_cfg["verbosity"] > 3: | |
247 pkk_fatal(u"Invalid verbosity level value {0}.".format(pkk_cfg["verbosity"])) | |
248 | |
249 | |
6 | 250 ### Handle each input file |
0 | 251 for filename in pkk_filenames: |
252 # Parse XML file into element tree | |
253 try: | |
254 uxml = xmlET.parse(filename) | |
255 except Exception as e: | |
256 pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e))) | |
257 | |
258 # Dump output | |
259 try: | |
260 xroot = uxml.getroot() | |
261 for dnode in xroot.findall("./DictionaryEntry"): | |
7 | 262 |
263 if pkk_cfg["debug"] and dnode.attrib["identifier"] not in pkk_debug_list: | |
264 continue | |
265 | |
0 | 266 if pkk_cfg["dump"]: |
7 | 267 pkk_dump_recursive(0, dnode) |
0 | 268 else: |
7 | 269 pkk_output_node(0, dnode) |
270 | |
271 print("\n") | |
0 | 272 |
273 except (BrokenPipeError, IOError) as e: | |
274 sys.stderr.close() | |
275 sys.exit(1) | |
276 | |
277 pkk_cleanup() | |
278 sys.exit(0) |