Mercurial > hg > lxmldump
annotate lxmldump.py @ 21:7ef08e05a5bf
Cleanup.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 11 May 2021 18:37:53 +0300 |
parents | f274504eafd0 |
children | 76856fc4e5fa |
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 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
16 import argparse |
0 | 17 |
18 assert sys.version_info >= (3, 7) | |
19 | |
20 | |
21 ### | |
22 ### Default settings | |
23 ### | |
7 | 24 pkk_str_fmap = { |
25 "Fragment" : ["<", ">"], | |
26 } | |
27 | |
28 | |
29 pkk_debug_list = [ | |
30 "ahas", | |
31 "ahavakkaine", | |
32 "ahavakala", | |
33 "ahavakoittuo", | |
34 "ahvaliha", | |
9 | 35 "aloilleh", |
18 | 36 "hanjahtoakseh", |
19 | 37 "akkalisto", |
7 | 38 ] |
39 | |
40 | |
21 | 41 # Operation modes |
42 PKK_MODE_NORMAL = 0 | |
43 PKK_MODE_DUMP = 1 | |
44 PKK_MODE_XML = 2 | |
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: |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
57 if pkk_cfg.normalize: |
12 | 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): |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
73 return pkk_cfg.verbosity >= lvl |
8 | 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): |
16 | 96 return "<PTR:{}>{}</PTR>".format( |
10 | 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 |
16 | 102 def pkk_node_to_text(lnode): |
7 | 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() |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
110 if pkk_cfg.annotate and isinstance(pnode.tag, str) and pnode.tag in pkk_str_fmap: |
9 | 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"]: | |
16 | 124 stmp = pkk_node_to_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 | |
17 | 144 ## Output item(s) under given node with given format string |
13 | 145 def pkk_output_subs_fmt(indent, dnode, dsub, dname, dfmt): |
7 | 146 for qnode in dnode.findall(dsub): |
16 | 147 pkk_printi(indent, dfmt.format(dname, pkk_node_to_text(qnode))) |
7 | 148 |
17 | 149 ## Output item(s) under given node with a prefixed name string |
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 | |
17 | 154 ## Output a main "Headword" or "Sense" node under it |
7 | 155 def pkk_output_sense(indent, dnode): |
17 | 156 # Search form and definition |
13 | 157 pkk_output_subs_prefix(indent, dnode, "./SearchForm", "srch") |
158 pkk_output_subs_prefix(indent, dnode, "./Definition", "defn") | |
7 | 159 |
17 | 160 # Examples |
7 | 161 for wnode in dnode.findall("./ExampleBlock/ExampleCtn"): |
16 | 162 sstr = pkk_node_to_text(wnode.find("./Example")) |
8 | 163 lstr = "" |
6 | 164 |
8 | 165 if pkk_verbosity(1): |
166 ltmp = [] | |
167 for qnode in wnode.findall("./FreeTopic[@type='levikki']/GeographicalUsage"): | |
16 | 168 ltmp.append("{} [{}]".format(pkk_node_to_text(qnode), qnode.attrib["class"])) |
8 | 169 |
170 if len(ltmp) > 0: | |
171 lstr = " ({})".format(", ".join(ltmp)) | |
7 | 172 |
173 pkk_printi(indent + 1, "{} \"{}\"{}\n".format("exmp", sstr, lstr)) | |
174 | |
175 | |
17 | 176 ## Output one "DictionaryEntry" node |
7 | 177 def pkk_output_node(indent, dnode): |
6 | 178 |
7 | 179 for wnode in dnode.findall("./HeadwordCtn"): |
18 | 180 # Create list with grammatical attributes (noun, verb, etc.) |
181 tmpl = [] | |
182 for pnode in wnode.findall("./PartOfSpeechCtn/PartOfSpeech"): | |
183 tmpl.append(pnode.attrib["freeValue"]) | |
184 | |
185 for pnode in wnode.findall("./GrammaticalNote"): | |
19 | 186 tmpl.append(pkk_node_to_text(pnode)) |
18 | 187 |
188 # Remove duplicates and sort the list | |
189 tmpl = list(set(tmpl)) | |
190 tmpl.sort(reverse=False, key=lambda attr: (attr, len(attr))) | |
191 | |
192 # Print the headword and attributes if any | |
193 pkk_output_subs_fmt(indent, wnode, "./Headword", "", "\"{1}\"") | |
194 if len(tmpl) > 0: | |
195 pkk_print(" ({})\n".format(" ; ".join(tmpl))) | |
196 else: | |
197 pkk_print("\n") | |
198 | |
199 # Print main "sense" | |
7 | 200 pkk_output_sense(indent + 1, wnode) |
6 | 201 |
18 | 202 # Print any other "senses" |
7 | 203 index = 1 |
204 for wnode in dnode.findall("./SenseGrp"): | |
8 | 205 pkk_printi(indent + 1, "sense #{}\n".format(index)) |
7 | 206 pkk_output_sense(indent + 2, wnode) |
207 index += 1 | |
6 | 208 |
209 | |
0 | 210 ### |
211 ### Main program starts | |
212 ### | |
213 signal.signal(signal.SIGINT, pkk_signal_handler) | |
214 | |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
215 optparser = argparse.ArgumentParser( |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
216 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
|
217 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
|
218 epilog="\n\n" |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
219 ) |
0 | 220 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
221 optparser.add_argument("filenames", action="extend", nargs="*", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
222 type=str, metavar="filename", help="XML filename(s)") |
0 | 223 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
224 optparser.add_argument("-d", "--dump", |
21 | 225 action="store_const", const=PKK_MODE_DUMP, default=PKK_MODE_NORMAL, |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
226 dest="mode", help="output as simple dump") |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
227 |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
228 optparser.add_argument("-x", "--xml", |
21 | 229 action="store_const", const=PKK_MODE_XML, |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
230 dest="mode", help="output as XML") |
0 | 231 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
232 optparser.add_argument("-n", "--normalize", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
233 action="store_const", const=True, default=False, |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
234 dest="normalize", help="output NFC normalized Unicode") |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
235 |
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("-a", "--annotate", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
237 action="store_const", const=True, default=False, |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
238 dest="annotate", help="annotate strings") |
0 | 239 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
240 optparser.add_argument("-v", "--verbosity", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
241 type=int, choices=range(0,4), default=3, |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
242 metavar="n", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
243 dest="verbosity", help='set verbosity level (0-3, default: %(default)s)') |
0 | 244 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
245 optparser.add_argument("-p", "--debug", |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
246 action="store_const", const=True, default=False, |
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
247 dest="debug", help=argparse.SUPPRESS) |
0 | 248 |
249 | |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
250 ### 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
|
251 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
|
252 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
|
253 optparser.print_help() |
0 | 254 sys.exit(0) |
255 | |
256 | |
6 | 257 ### 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
|
258 for filename in pkk_cfg.filenames: |
0 | 259 # Parse XML file into element tree |
260 try: | |
261 uxml = xmlET.parse(filename) | |
262 except Exception as e: | |
263 pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e))) | |
264 | |
265 # Dump output | |
266 try: | |
267 xroot = uxml.getroot() | |
268 for dnode in xroot.findall("./DictionaryEntry"): | |
7 | 269 |
20
f274504eafd0
Use Python argparse module instead of custom self-rolled argument parser.
Matti Hamalainen <ccr@tnsp.org>
parents:
19
diff
changeset
|
270 if pkk_cfg.debug and dnode.attrib["identifier"] not in pkk_debug_list: |
7 | 271 continue |
272 | |
21 | 273 if pkk_cfg.mode == PKK_MODE_NORMAL: |
19 | 274 try: |
275 pkk_output_node(0, dnode) | |
276 except Exception as e: | |
277 pkk_dump_recursive(0, dnode) | |
278 print(str(e)) | |
279 sys.exit(0) | |
21 | 280 elif pkk_cfg.mode == PKK_MODE_DUMP: |
7 | 281 pkk_dump_recursive(0, dnode) |
21 | 282 elif pkk_cfg.mode == PKK_MODE_XML: |
10 | 283 pkk_print(str(xmlET.tostring(dnode, encoding="utf8")) + "\n") |
0 | 284 else: |
10 | 285 pkk_fatal("Invalid operation mode?") |
7 | 286 |
287 print("\n") | |
0 | 288 |
289 except (BrokenPipeError, IOError) as e: | |
290 sys.stderr.close() | |
291 sys.exit(1) | |
292 | |
293 pkk_cleanup() | |
294 sys.exit(0) |