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