Mercurial > hg > lxmldump
annotate lxmldump.py @ 26:420f13925f20
Rename a variable.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 25 May 2021 11:39:36 +0300 |
parents | 8a6738f67106 |
children | d77ab8a300b1 |
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 ### | |
23 | 8 ### Released / distributed under 3-clause BSD license |
9 ### (see file "COPYING" for more information) | |
10 ### | |
4 | 11 ### Python 3.7+ required! |
0 | 12 ### |
13 import sys | |
14 import signal | |
15 import re | |
16 from pathlib import Path | |
17 import xml.etree.ElementTree as xmlET | |
5
274b2091137c
Some more work on cleaning this up.
Matti Hamalainen <ccr@tnsp.org>
parents:
4
diff
changeset
|
18 import unicodedata |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
19 import argparse |
0 | 20 |
21 assert sys.version_info >= (3, 7) | |
22 | |
23 | |
24 ### | |
25 ### Default settings | |
26 ### | |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
27 # Operation modes |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
28 PKK_MODE_NORMAL = 0 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
29 PKK_MODE_DUMP = 1 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
30 PKK_MODE_XML = 2 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
31 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
32 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
33 # Element annotation mappings |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
34 pkk_element_annotation_map = { |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
35 "Fragment" : { |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
36 PKK_MODE_NORMAL: ["<", ">"], |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
37 }, |
7 | 38 } |
39 | |
40 | |
41 pkk_debug_list = [ | |
42 "ahas", | |
43 "ahavakkaine", | |
44 "ahavakala", | |
45 "ahavakoittuo", | |
46 "ahvaliha", | |
9 | 47 "aloilleh", |
18 | 48 "hanjahtoakseh", |
19 | 49 "akkalisto", |
7 | 50 ] |
51 | |
52 | |
21 | 53 |
0 | 54 ### |
55 ### Misc. helper functions, etc | |
56 ### | |
57 def pkk_cleanup(): | |
58 return 0 | |
59 | |
60 | |
13 | 61 ## 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
|
62 def pkk_print(smsg): |
12 | 63 try: |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
64 if pkk_cfg.normalize: |
12 | 65 sys.stdout.write(unicodedata.normalize("NFC", smsg)) |
66 else: | |
67 sys.stdout.write(smsg) | |
68 | |
69 except (BrokenPipeError, IOError) as e: | |
70 sys.stderr.close() | |
71 | |
0 | 72 |
13 | 73 ## Print string with indentation |
7 | 74 def pkk_printi(indent, smsg): |
22 | 75 pkk_print((" " * pkk_cfg.indent * indent) + smsg) |
7 | 76 |
0 | 77 |
78 ## Fatal error handler | |
79 def pkk_fatal(smsg): | |
80 print(u"ERROR: "+ smsg) | |
81 sys.exit(1) | |
82 | |
83 | |
84 ## Handler for SIGINT signals | |
85 def pkk_signal_handler(signal, frame): | |
86 pkk_cleanup() | |
87 print(u"\nQuitting due to SIGINT / Ctrl+C!") | |
88 sys.exit(1) | |
89 | |
90 | |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
91 ## Annotate string |
26 | 92 def pkk_str_annotate(mtag, mstr): |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
93 if pkk_cfg.annotate and mtag in pkk_element_annotation_map: |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
94 if pkk_cfg.mode in pkk_element_annotation_map[mtag]: |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
95 mmode = pkk_cfg.mode |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
96 else: |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
97 mmode = PKK_MODE_NORMAL |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
98 |
26 | 99 return pkk_element_annotation_map[mtag][mmode][0] + mstr + pkk_element_annotation_map[mtag][mmode][1] |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
100 else: |
26 | 101 return mstr |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
102 |
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
103 |
13 | 104 ## Clean string by removing tabs and newlines |
10 | 105 def pkk_str_clean(mstr): |
106 return re.sub(r'[\n\r\t]', '', mstr) | |
107 | |
108 | |
13 | 109 ## Format "Ptr" node as text |
9 | 110 def pkk_ptr_to_text(pnode): |
16 | 111 return "<PTR:{}>{}</PTR>".format( |
10 | 112 pnode.attrib["{http://www.w3.org/TR/xlink}href"], |
113 ("".join(pnode.itertext())).strip()) | |
9 | 114 |
115 | |
13 | 116 ## Get text inside a given node |
16 | 117 def pkk_node_to_text(lnode): |
7 | 118 stmp = "" |
119 for pnode in lnode.iter(): | |
9 | 120 if pnode.tag == "Ptr": |
121 stmp += pkk_ptr_to_text(pnode) | |
122 else: | |
123 if isinstance(pnode.text, str): | |
25
8a6738f67106
Factor string annotation into separate function.
Matti Hamalainen <ccr@tnsp.org>
parents:
24
diff
changeset
|
124 stmp += pkk_str_annotate(pnode.tag, pkk_str_clean(pnode.text).strip()) |
7 | 125 |
9 | 126 if isinstance(pnode.tail, str): |
10 | 127 stmp += pkk_str_clean(pnode.tail) |
7 | 128 |
129 return stmp.strip() | |
130 | |
131 | |
13 | 132 ## Simple recursive dump starting at given node |
7 | 133 def pkk_dump_recursive(indent, lnode): |
134 if lnode.tag in ["Example"]: | |
16 | 135 stmp = pkk_node_to_text(lnode) |
9 | 136 pkk_printi(indent, "{} \"{}\"\n".format(lnode.tag, stmp)) |
6 | 137 else: |
7 | 138 if isinstance(lnode.text, str): |
10 | 139 stmp = pkk_str_clean(lnode.text).strip() |
7 | 140 if stmp != "": |
141 stmp = " \""+ stmp +"\"" | |
142 else: | |
143 stmp = "" | |
6 | 144 |
145 if len(lnode.attrib) > 0: | |
10 | 146 atmp = " "+ str(lnode.attrib) |
6 | 147 else: |
148 atmp = "" | |
149 | |
7 | 150 pkk_printi(indent, "{}{}{}\n".format(lnode.tag, atmp, stmp)) |
6 | 151 for qnode in lnode.findall("./*"): |
7 | 152 pkk_dump_recursive(indent + 1, qnode) |
6 | 153 |
154 | |
17 | 155 ## Output item(s) under given node with given format string |
13 | 156 def pkk_output_subs_fmt(indent, dnode, dsub, dname, dfmt): |
7 | 157 for qnode in dnode.findall(dsub): |
16 | 158 pkk_printi(indent, dfmt.format(dname, pkk_node_to_text(qnode))) |
7 | 159 |
17 | 160 ## Output item(s) under given node with a prefixed name string |
13 | 161 def pkk_output_subs_prefix(indent, dnode, dsub, dname): |
162 pkk_output_subs_fmt(indent, dnode, dsub, dname, "{0} \"{1}\"\n") | |
7 | 163 |
164 | |
17 | 165 ## Output a main "Headword" or "Sense" node under it |
7 | 166 def pkk_output_sense(indent, dnode): |
17 | 167 # Search form and definition |
13 | 168 pkk_output_subs_prefix(indent, dnode, "./SearchForm", "srch") |
169 pkk_output_subs_prefix(indent, dnode, "./Definition", "defn") | |
7 | 170 |
17 | 171 # Examples |
7 | 172 for wnode in dnode.findall("./ExampleBlock/ExampleCtn"): |
16 | 173 sstr = pkk_node_to_text(wnode.find("./Example")) |
8 | 174 lstr = "" |
6 | 175 |
24
8c8e8e4504bb
Remove verbosity option as it is not really used.
Matti Hamalainen <ccr@tnsp.org>
parents:
23
diff
changeset
|
176 ltmp = [] |
8c8e8e4504bb
Remove verbosity option as it is not really used.
Matti Hamalainen <ccr@tnsp.org>
parents:
23
diff
changeset
|
177 for qnode in wnode.findall("./FreeTopic[@type='levikki']/GeographicalUsage"): |
8c8e8e4504bb
Remove verbosity option as it is not really used.
Matti Hamalainen <ccr@tnsp.org>
parents:
23
diff
changeset
|
178 ltmp.append("{} [{}]".format(pkk_node_to_text(qnode), qnode.attrib["class"])) |
8 | 179 |
24
8c8e8e4504bb
Remove verbosity option as it is not really used.
Matti Hamalainen <ccr@tnsp.org>
parents:
23
diff
changeset
|
180 if len(ltmp) > 0: |
8c8e8e4504bb
Remove verbosity option as it is not really used.
Matti Hamalainen <ccr@tnsp.org>
parents:
23
diff
changeset
|
181 lstr = " ({})".format(", ".join(ltmp)) |
7 | 182 |
183 pkk_printi(indent + 1, "{} \"{}\"{}\n".format("exmp", sstr, lstr)) | |
184 | |
185 | |
17 | 186 ## Output one "DictionaryEntry" node |
7 | 187 def pkk_output_node(indent, dnode): |
6 | 188 |
7 | 189 for wnode in dnode.findall("./HeadwordCtn"): |
18 | 190 # Create list with grammatical attributes (noun, verb, etc.) |
191 tmpl = [] | |
192 for pnode in wnode.findall("./PartOfSpeechCtn/PartOfSpeech"): | |
193 tmpl.append(pnode.attrib["freeValue"]) | |
194 | |
195 for pnode in wnode.findall("./GrammaticalNote"): | |
19 | 196 tmpl.append(pkk_node_to_text(pnode)) |
18 | 197 |
198 # Remove duplicates and sort the list | |
199 tmpl = list(set(tmpl)) | |
200 tmpl.sort(reverse=False, key=lambda attr: (attr, len(attr))) | |
201 | |
202 # Print the headword and attributes if any | |
203 pkk_output_subs_fmt(indent, wnode, "./Headword", "", "\"{1}\"") | |
204 if len(tmpl) > 0: | |
205 pkk_print(" ({})\n".format(" ; ".join(tmpl))) | |
206 else: | |
207 pkk_print("\n") | |
208 | |
209 # Print main "sense" | |
7 | 210 pkk_output_sense(indent + 1, wnode) |
6 | 211 |
18 | 212 # Print any other "senses" |
7 | 213 index = 1 |
214 for wnode in dnode.findall("./SenseGrp"): | |
8 | 215 pkk_printi(indent + 1, "sense #{}\n".format(index)) |
7 | 216 pkk_output_sense(indent + 2, wnode) |
217 index += 1 | |
6 | 218 |
219 | |
0 | 220 ### |
221 ### Main program starts | |
222 ### | |
223 signal.signal(signal.SIGINT, pkk_signal_handler) | |
224 | |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
225 optparser = argparse.ArgumentParser( |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
226 description="lxmldump - Dump ISO/FDIS 1951 XML file data", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
227 usage="%(prog)s [options] <input xml file(s)>", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
228 epilog="\n\n" |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
229 ) |
0 | 230 |
22 | 231 optparser.add_argument("filenames", |
232 type=str, action="extend", nargs="*", | |
233 metavar="filename", | |
234 help="XML filename(s)") | |
0 | 235 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
236 optparser.add_argument("-d", "--dump", |
22 | 237 dest="mode", |
21 | 238 action="store_const", const=PKK_MODE_DUMP, default=PKK_MODE_NORMAL, |
22 | 239 help="output as simple dump") |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
240 |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
241 optparser.add_argument("-x", "--xml", |
22 | 242 dest="mode", |
21 | 243 action="store_const", const=PKK_MODE_XML, |
22 | 244 help="output as XML") |
0 | 245 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
246 optparser.add_argument("-n", "--normalize", |
22 | 247 dest="normalize", |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
248 action="store_const", const=True, default=False, |
22 | 249 help="output NFC normalized Unicode") |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
250 |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
251 optparser.add_argument("-a", "--annotate", |
22 | 252 dest="annotate", |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
253 action="store_const", const=True, default=False, |
22 | 254 help="annotate strings") |
0 | 255 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
256 optparser.add_argument("-p", "--debug", |
22 | 257 dest="debug", action="store_const", const=True, default=False, |
258 help=argparse.SUPPRESS) | |
259 | |
260 optparser.add_argument("-i", "--indent", | |
261 dest="indent", | |
262 type=int, choices=range(0, 32), default=4, | |
263 metavar="n", | |
264 help='indent output by <n> characters (default: %(default)s)') | |
0 | 265 |
266 | |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
267 ### Show help if needed |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
268 pkk_cfg = optparser.parse_args() |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
269 if len(pkk_cfg.filenames) == 0: |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
270 optparser.print_help() |
0 | 271 sys.exit(0) |
272 | |
273 | |
6 | 274 ### Handle each input file |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
275 for filename in pkk_cfg.filenames: |
0 | 276 # Parse XML file into element tree |
277 try: | |
278 uxml = xmlET.parse(filename) | |
279 except Exception as e: | |
280 pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e))) | |
281 | |
282 # Dump output | |
283 try: | |
284 xroot = uxml.getroot() | |
285 for dnode in xroot.findall("./DictionaryEntry"): | |
7 | 286 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
287 if pkk_cfg.debug and dnode.attrib["identifier"] not in pkk_debug_list: |
7 | 288 continue |
289 | |
21 | 290 if pkk_cfg.mode == PKK_MODE_NORMAL: |
19 | 291 try: |
292 pkk_output_node(0, dnode) | |
293 except Exception as e: | |
294 pkk_dump_recursive(0, dnode) | |
295 print(str(e)) | |
296 sys.exit(0) | |
21 | 297 elif pkk_cfg.mode == PKK_MODE_DUMP: |
7 | 298 pkk_dump_recursive(0, dnode) |
21 | 299 elif pkk_cfg.mode == PKK_MODE_XML: |
10 | 300 pkk_print(str(xmlET.tostring(dnode, encoding="utf8")) + "\n") |
0 | 301 else: |
10 | 302 pkk_fatal("Invalid operation mode?") |
7 | 303 |
304 print("\n") | |
0 | 305 |
306 except (BrokenPipeError, IOError) as e: | |
307 sys.stderr.close() | |
308 sys.exit(1) | |
309 | |
310 pkk_cleanup() | |
311 sys.exit(0) |