Mercurial > hg > lxmldump
annotate lxmldump.py @ 18:ff959de0f6c8
Add grammatical attributes.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 11 May 2021 15:44:33 +0300 |
parents | 6fa24c711f86 |
children | 7c6eb57798bd |
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", |
18 | 44 "hanjahtoakseh", |
7 | 45 ] |
46 | |
47 | |
0 | 48 ### |
49 ### Misc. helper functions, etc | |
50 ### | |
51 def pkk_cleanup(): | |
52 return 0 | |
53 | |
54 | |
13 | 55 ## 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
|
56 def pkk_print(smsg): |
12 | 57 try: |
58 if pkk_cfg["normalize"]: | |
59 sys.stdout.write(unicodedata.normalize("NFC", smsg)) | |
60 else: | |
61 sys.stdout.write(smsg) | |
62 | |
63 except (BrokenPipeError, IOError) as e: | |
64 sys.stderr.close() | |
65 | |
0 | 66 |
13 | 67 ## Print string with indentation |
7 | 68 def pkk_printi(indent, smsg): |
69 pkk_print((" " * indent) + smsg) | |
70 | |
0 | 71 |
13 | 72 ## Check value against current verbosity level |
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 | |
13 | 90 ## Clean string by removing tabs and newlines |
10 | 91 def pkk_str_clean(mstr): |
92 return re.sub(r'[\n\r\t]', '', mstr) | |
93 | |
94 | |
13 | 95 ## Format "Ptr" node as text |
9 | 96 def pkk_ptr_to_text(pnode): |
16 | 97 return "<PTR:{}>{}</PTR>".format( |
10 | 98 pnode.attrib["{http://www.w3.org/TR/xlink}href"], |
99 ("".join(pnode.itertext())).strip()) | |
9 | 100 |
101 | |
13 | 102 ## Get text inside a given node |
16 | 103 def pkk_node_to_text(lnode): |
7 | 104 stmp = "" |
105 for pnode in lnode.iter(): | |
9 | 106 if pnode.tag == "Ptr": |
107 stmp += pkk_ptr_to_text(pnode) | |
108 else: | |
109 if isinstance(pnode.text, str): | |
10 | 110 ptext = pkk_str_clean(pnode.text).strip() |
9 | 111 if pkk_cfg["annotate"] and isinstance(pnode.tag, str) and pnode.tag in pkk_str_fmap: |
112 stmp += pkk_str_fmap[pnode.tag][0] + ptext + pkk_str_fmap[pnode.tag][1] | |
113 else: | |
114 stmp += ptext | |
7 | 115 |
9 | 116 if isinstance(pnode.tail, str): |
10 | 117 stmp += pkk_str_clean(pnode.tail) |
7 | 118 |
119 return stmp.strip() | |
120 | |
121 | |
13 | 122 ## Simple recursive dump starting at given node |
7 | 123 def pkk_dump_recursive(indent, lnode): |
124 if lnode.tag in ["Example"]: | |
16 | 125 stmp = pkk_node_to_text(lnode) |
9 | 126 pkk_printi(indent, "{} \"{}\"\n".format(lnode.tag, stmp)) |
6 | 127 else: |
7 | 128 if isinstance(lnode.text, str): |
10 | 129 stmp = pkk_str_clean(lnode.text).strip() |
7 | 130 if stmp != "": |
131 stmp = " \""+ stmp +"\"" | |
132 else: | |
133 stmp = "" | |
6 | 134 |
135 if len(lnode.attrib) > 0: | |
10 | 136 atmp = " "+ str(lnode.attrib) |
6 | 137 else: |
138 atmp = "" | |
139 | |
7 | 140 pkk_printi(indent, "{}{}{}\n".format(lnode.tag, atmp, stmp)) |
6 | 141 for qnode in lnode.findall("./*"): |
7 | 142 pkk_dump_recursive(indent + 1, qnode) |
6 | 143 |
144 | |
17 | 145 ## Output item(s) under given node with given format string |
13 | 146 def pkk_output_subs_fmt(indent, dnode, dsub, dname, dfmt): |
7 | 147 for qnode in dnode.findall(dsub): |
16 | 148 pkk_printi(indent, dfmt.format(dname, pkk_node_to_text(qnode))) |
7 | 149 |
17 | 150 ## Output item(s) under given node with a prefixed name string |
13 | 151 def pkk_output_subs_prefix(indent, dnode, dsub, dname): |
152 pkk_output_subs_fmt(indent, dnode, dsub, dname, "{0} \"{1}\"\n") | |
7 | 153 |
154 | |
17 | 155 ## Output a main "Headword" or "Sense" node under it |
7 | 156 def pkk_output_sense(indent, dnode): |
17 | 157 # Search form and definition |
13 | 158 pkk_output_subs_prefix(indent, dnode, "./SearchForm", "srch") |
159 pkk_output_subs_prefix(indent, dnode, "./Definition", "defn") | |
7 | 160 |
17 | 161 # Examples |
7 | 162 for wnode in dnode.findall("./ExampleBlock/ExampleCtn"): |
16 | 163 sstr = pkk_node_to_text(wnode.find("./Example")) |
8 | 164 lstr = "" |
6 | 165 |
8 | 166 if pkk_verbosity(1): |
167 ltmp = [] | |
168 for qnode in wnode.findall("./FreeTopic[@type='levikki']/GeographicalUsage"): | |
16 | 169 ltmp.append("{} [{}]".format(pkk_node_to_text(qnode), qnode.attrib["class"])) |
8 | 170 |
171 if len(ltmp) > 0: | |
172 lstr = " ({})".format(", ".join(ltmp)) | |
7 | 173 |
174 pkk_printi(indent + 1, "{} \"{}\"{}\n".format("exmp", sstr, lstr)) | |
175 | |
176 | |
17 | 177 ## Output one "DictionaryEntry" node |
7 | 178 def pkk_output_node(indent, dnode): |
6 | 179 |
7 | 180 for wnode in dnode.findall("./HeadwordCtn"): |
18 | 181 # Create list with grammatical attributes (noun, verb, etc.) |
182 tmpl = [] | |
183 for pnode in wnode.findall("./PartOfSpeechCtn/PartOfSpeech"): | |
184 tmpl.append(pnode.attrib["freeValue"]) | |
185 | |
186 for pnode in wnode.findall("./GrammaticalNote"): | |
187 tmpl.append(pnode.text.strip()) | |
188 | |
189 # Remove duplicates and sort the list | |
190 tmpl = list(set(tmpl)) | |
191 tmpl.sort(reverse=False, key=lambda attr: (attr, len(attr))) | |
192 | |
193 # Print the headword and attributes if any | |
194 pkk_output_subs_fmt(indent, wnode, "./Headword", "", "\"{1}\"") | |
195 if len(tmpl) > 0: | |
196 pkk_print(" ({})\n".format(" ; ".join(tmpl))) | |
197 else: | |
198 pkk_print("\n") | |
199 | |
200 # Print main "sense" | |
7 | 201 pkk_output_sense(indent + 1, wnode) |
6 | 202 |
18 | 203 # Print any other "senses" |
7 | 204 index = 1 |
205 for wnode in dnode.findall("./SenseGrp"): | |
8 | 206 pkk_printi(indent + 1, "sense #{}\n".format(index)) |
7 | 207 pkk_output_sense(indent + 2, wnode) |
208 index += 1 | |
6 | 209 |
210 | |
0 | 211 ### |
212 ### Main program starts | |
213 ### | |
214 signal.signal(signal.SIGINT, pkk_signal_handler) | |
215 | |
216 | |
217 ### Check if we have arguments | |
218 pkk_show_help = False | |
219 pkk_filenames = [] | |
220 argc = 1 | |
221 while argc < len(sys.argv): | |
222 arg = sys.argv[argc] | |
223 | |
224 needs_param = False | |
225 if argc + 1 < len(sys.argv): | |
226 param = sys.argv[argc + 1] | |
227 else: | |
228 param = None | |
229 | |
230 # Check for option type arg | |
231 if arg[0:1] == "-": | |
232 oarg = arg | |
233 arg = arg.lstrip("-") | |
234 | |
235 if arg == "help" or arg == "h": | |
236 pkk_show_help = True | |
237 elif arg == "dump" or arg == "d": | |
10 | 238 pkk_cfg["mode"] = 1 |
239 elif arg == "xml" or arg == "x": | |
240 pkk_cfg["mode"] = 2 | |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
241 elif arg == "normalize" or arg == "n": |
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
242 pkk_cfg["normalize"] = True |
8 | 243 elif arg == "annotate" or arg == "a": |
244 pkk_cfg["annotate"] = True | |
7 | 245 elif arg == "p": |
246 pkk_cfg["debug"] = True | |
8 | 247 elif arg == "verbosity" or arg == "v": |
248 needs_param = True | |
249 pkk_cfg["verbosity"] = param | |
0 | 250 else: |
251 pkk_fatal(u"Invalid option argument '{0}'.".format(oarg)) | |
252 | |
253 if needs_param and param == None: | |
254 pkk_fatal(u"Option '{0}' requires an argument.".format(oarg)) | |
255 else: | |
256 # Non-option argument | |
257 pkk_filenames.append(arg) | |
258 | |
259 if needs_param: | |
260 argc += 2 | |
261 else: | |
262 argc += 1 | |
263 | |
264 | |
265 ### Show help if requested | |
266 if pkk_show_help or len(pkk_filenames) == 0: | |
267 print(u"lxmldump - Dump ISO/FDIS 1951 XML file data") | |
268 print(u"Usage: {0} <options> <input xml file(s)>". | |
269 format(str(Path(sys.argv[0]).name))) | |
270 print(u"") | |
271 print(u" --help Show this help") | |
15 | 272 print(u" -d, --dump Output as simple dump") |
273 print(u" -x, --xml Output as XML") | |
6 | 274 print(u" -n, --normalize Output NFC normalized Unicode") |
8 | 275 print(u" -a, --annotate Annotate strings") |
276 print(u" -v, --verbosity <n> Set verbosity level (0 - 3)") | |
0 | 277 print(u"") |
278 sys.exit(0) | |
279 | |
280 | |
8 | 281 ### Validate settings |
282 try: | |
283 pkk_cfg["verbosity"] = int(pkk_cfg["verbosity"]) | |
284 except Exception as e: | |
285 pkk_fatal(u"Verbosity level is not a valid integer.") | |
286 if pkk_cfg["verbosity"] < 0 or pkk_cfg["verbosity"] > 3: | |
287 pkk_fatal(u"Invalid verbosity level value {0}.".format(pkk_cfg["verbosity"])) | |
288 | |
289 | |
6 | 290 ### Handle each input file |
0 | 291 for filename in pkk_filenames: |
292 # Parse XML file into element tree | |
293 try: | |
294 uxml = xmlET.parse(filename) | |
295 except Exception as e: | |
296 pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e))) | |
297 | |
298 # Dump output | |
299 try: | |
300 xroot = uxml.getroot() | |
301 for dnode in xroot.findall("./DictionaryEntry"): | |
7 | 302 |
303 if pkk_cfg["debug"] and dnode.attrib["identifier"] not in pkk_debug_list: | |
304 continue | |
305 | |
10 | 306 if pkk_cfg["mode"] == 0: |
307 pkk_output_node(0, dnode) | |
308 elif pkk_cfg["mode"] == 1: | |
7 | 309 pkk_dump_recursive(0, dnode) |
10 | 310 elif pkk_cfg["mode"] == 2: |
311 pkk_print(str(xmlET.tostring(dnode, encoding="utf8")) + "\n") | |
0 | 312 else: |
10 | 313 pkk_fatal("Invalid operation mode?") |
7 | 314 |
315 print("\n") | |
0 | 316 |
317 except (BrokenPipeError, IOError) as e: | |
318 sys.stderr.close() | |
319 sys.exit(1) | |
320 | |
321 pkk_cleanup() | |
322 sys.exit(0) |