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