| 1 |
#!/usr/bin/python3 |
| 2 |
# |
| 3 |
# Copyright (C) 2018 Xavi Ivars <[email protected]> |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or |
| 6 |
# modify it under the terms of the GNU General Public License as |
| 7 |
# published by the Free Software Foundation; either version 2 of the |
| 8 |
# License, or (at your option) any later version. |
| 9 |
# |
| 10 |
# This program is distributed in the hope that it will be useful, but |
| 11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 |
# General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with this program; if not, see <https://www.gnu.org/licenses/>. |
| 17 |
# |
| 18 |
|
| 19 |
from xml.sax import handler, saxutils, make_parser |
| 20 |
import sys |
| 21 |
|
| 22 |
vl_other = "other" |
| 23 |
|
| 24 |
alternative = sys.argv[1] |
| 25 |
dixfile = sys.argv[2] |
| 26 |
|
| 27 |
if alternative == "other": |
| 28 |
vl_other = vl_other[::-1] # reverse string |
| 29 |
|
| 30 |
def printAttrs(attrsmap): |
| 31 |
if len(attrsmap) == 0: |
| 32 |
return "" |
| 33 |
output = [] |
| 34 |
for (i,j) in list(attrsmap.items()): |
| 35 |
output.append(i) |
| 36 |
output.append("=\"") |
| 37 |
output.append(saxutils.escape(j)) |
| 38 |
output.append("\" ") |
| 39 |
|
| 40 |
return " " + "".join(output).strip() |
| 41 |
|
| 42 |
class DixHandler(handler.ContentHandler): |
| 43 |
def __init__(self, out = sys.stdout): |
| 44 |
handler.ContentHandler.__init__(self) |
| 45 |
self._out = out |
| 46 |
self._buf = [] |
| 47 |
|
| 48 |
def flush(self): |
| 49 |
for i in self._buf: |
| 50 |
self._out.write(i) |
| 51 |
self._buf = [] |
| 52 |
|
| 53 |
def startElement(self, name, attrs): |
| 54 |
if name == "e" and "vl" in attrs: |
| 55 |
attrs2 = {i:j for (i,j) in list(attrs.items()) if i != "vl"} |
| 56 |
vals = attrs["vl"].split() |
| 57 |
if alternative in vals: |
| 58 |
attrs2["vl"] = alternative |
| 59 |
else: |
| 60 |
attrs2["vl"] = vl_other |
| 61 |
attrs = attrs2 |
| 62 |
self._buf.append("<" + name + printAttrs(attrs) + ">") |
| 63 |
|
| 64 |
def endElement(self, name): |
| 65 |
if len(self._buf) > 0 and self._buf[-1][0:1] == "<" and self._buf[-1][-1:] == ">" and self._buf[-1][1:2] != "/": |
| 66 |
self._buf[-1] = self._buf[-1][0:-1]+"/>" |
| 67 |
self.flush() |
| 68 |
else: |
| 69 |
self.flush() |
| 70 |
self._out.write("</") |
| 71 |
self._out.write(name) |
| 72 |
self._out.write(">") |
| 73 |
|
| 74 |
def characters(self, content): |
| 75 |
self.flush() |
| 76 |
self._out.write(saxutils.escape(content)) |
| 77 |
|
| 78 |
parser = make_parser() |
| 79 |
parser.setContentHandler(DixHandler()) |
| 80 |
|
| 81 |
with open(dixfile, "r", encoding="utf-8") as f: |
| 82 |
parser.parse(f) |