Mercurial > hg > lxmldump
annotate lxmldump.py @ 14:7498bda8b4a2
Cleanup.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 11 May 2021 13:15:07 +0300 |
parents | 3bd772fd6a50 |
children | 2f86537ff1f7 |
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 "annotate": False, | |
10 | 26 "mode": 0, |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
27 "normalize": False, |
7 | 28 "debug": False, |
0 | 29 } |
30 | |
31 | |
7 | 32 pkk_str_fmap = { |
33 "Fragment" : ["<", ">"], | |
34 } | |
35 | |
36 | |
37 pkk_debug_list = [ | |
38 "ahas", | |
39 "ahavakkaine", | |
40 "ahavakala", | |
41 "ahavakoittuo", | |
42 "ahvaliha", | |
9 | 43 "aloilleh", |
7 | 44 ] |
45 | |
46 | |
0 | 47 ### |
48 ### Misc. helper functions, etc | |
49 ### | |
50 def pkk_cleanup(): | |
51 return 0 | |
52 | |
53 | |
13 | 54 ## Print string to stdout using normalized Unicode if enabled |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
55 def pkk_print(smsg): |
12 | 56 try: |
57 if pkk_cfg["normalize"]: | |
58 sys.stdout.write(unicodedata.normalize("NFC", smsg)) | |
59 else: | |
60 sys.stdout.write(smsg) | |
61 | |
62 except (BrokenPipeError, IOError) as e: | |
63 sys.stderr.close() | |
64 | |
0 | 65 |
13 | 66 ## Print string with indentation |
7 | 67 def pkk_printi(indent, smsg): |
68 pkk_print((" " * indent) + smsg) | |
69 | |
0 | 70 |
13 | 71 ## Check value against current verbosity level |
8 | 72 def pkk_verbosity(lvl): |
73 return pkk_cfg["verbosity"] >= lvl | |
74 | |
75 | |
0 | 76 ## Fatal error handler |
77 def pkk_fatal(smsg): | |
78 print(u"ERROR: "+ smsg) | |
79 sys.exit(1) | |
80 | |
81 | |
82 ## Handler for SIGINT signals | |
83 def pkk_signal_handler(signal, frame): | |
84 pkk_cleanup() | |
85 print(u"\nQuitting due to SIGINT / Ctrl+C!") | |
86 sys.exit(1) | |
87 | |
88 | |
13 | 89 ## Clean string by removing tabs and newlines |
10 | 90 def pkk_str_clean(mstr): |
91 return re.sub(r'[\n\r\t]', '', mstr) | |
92 | |
93 | |
13 | 94 ## Format "Ptr" node as text |
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 | |
13 | 101 ## Get text inside a given node |
7 | 102 def pkk_get_text(lnode): |
103 stmp = "" | |
104 for pnode in lnode.iter(): | |
9 | 105 if pnode.tag == "Ptr": |
106 stmp += pkk_ptr_to_text(pnode) | |
107 else: | |
108 if isinstance(pnode.text, str): | |
10 | 109 ptext = pkk_str_clean(pnode.text).strip() |
9 | 110 if pkk_cfg["annotate"] and isinstance(pnode.tag, str) and pnode.tag in pkk_str_fmap: |
111 stmp += pkk_str_fmap[pnode.tag][0] + ptext + pkk_str_fmap[pnode.tag][1] | |
112 else: | |
113 stmp += ptext | |
7 | 114 |
9 | 115 if isinstance(pnode.tail, str): |
10 | 116 stmp += pkk_str_clean(pnode.tail) |
7 | 117 |
118 return stmp.strip() | |
119 | |
120 | |
13 | 121 ## Simple recursive dump starting at given node |
7 | 122 def pkk_dump_recursive(indent, lnode): |
123 if lnode.tag in ["Example"]: | |
124 stmp = pkk_get_text(lnode) | |
9 | 125 pkk_printi(indent, "{} \"{}\"\n".format(lnode.tag, stmp)) |
6 | 126 else: |
7 | 127 if isinstance(lnode.text, str): |
10 | 128 stmp = pkk_str_clean(lnode.text).strip() |
7 | 129 if stmp != "": |
130 stmp = " \""+ stmp +"\"" | |
131 else: | |
132 stmp = "" | |
6 | 133 |
134 if len(lnode.attrib) > 0: | |
10 | 135 atmp = " "+ str(lnode.attrib) |
6 | 136 else: |
137 atmp = "" | |
138 | |
7 | 139 pkk_printi(indent, "{}{}{}\n".format(lnode.tag, atmp, stmp)) |
6 | 140 for qnode in lnode.findall("./*"): |
7 | 141 pkk_dump_recursive(indent + 1, qnode) |
6 | 142 |
143 | |
13 | 144 ## Output item under given node |
145 def pkk_output_subs_fmt(indent, dnode, dsub, dname, dfmt): | |
7 | 146 for qnode in dnode.findall(dsub): |
13 | 147 pkk_printi(indent, dfmt.format(dname, pkk_get_text(qnode))) |
7 | 148 |
12 | 149 |
13 | 150 def pkk_output_subs_prefix(indent, dnode, dsub, dname): |
151 pkk_output_subs_fmt(indent, dnode, dsub, dname, "{0} \"{1}\"\n") | |
7 | 152 |
153 | |
154 def pkk_output_sense(indent, dnode): | |
13 | 155 pkk_output_subs_prefix(indent, dnode, "./SearchForm", "srch") |
156 pkk_output_subs_prefix(indent, dnode, "./Definition", "defn") | |
7 | 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"): |
13 | 176 pkk_output_subs_fmt(indent, wnode, "./Headword", "", "\"{1}\":\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) |