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