| 1 |
#! /usr/bin/python3 |
| 2 |
|
| 3 |
""" |
| 4 |
Extract text from a .xml in a .docx file |
| 5 |
Reads the file from stdin |
| 6 |
""" |
| 7 |
|
| 8 |
import lxml.etree as ET |
| 9 |
import io |
| 10 |
import re |
| 11 |
import os, sys, argparse |
| 12 |
|
| 13 |
|
| 14 |
class docx(): |
| 15 |
|
| 16 |
def __init__(self, linies): |
| 17 |
self.parser = ET.XMLParser(remove_blank_text=True) |
| 18 |
self.tot = ET.fromstring("".join(lin.strip() for lin in linies).encode("utf8"), self.parser) |
| 19 |
self.pars = [paragraf(p) for p in docx.iter(self.tot, "w:p")] |
| 20 |
|
| 21 |
@staticmethod |
| 22 |
def iter(element, tag): |
| 23 |
ns, nom = tag.split(":") |
| 24 |
for e in element.iter("{%s}%s" % (docx.ns[ns], nom)): |
| 25 |
yield e |
| 26 |
|
| 27 |
ns = { |
| 28 |
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships", |
| 29 |
"wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", |
| 30 |
"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main", |
| 31 |
"w10": "urn:schemas-microsoft-com:office:word", |
| 32 |
"w14": "http://schemas.microsoft.com/office/word/2010/wordml", |
| 33 |
"wps": "http://schemas.microsoft.com/office/word/2010/wordprocessingShape", |
| 34 |
"wpg": "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup", |
| 35 |
"mc": "http://schemas.openxmlformats.org/markup-compatibility/2006", |
| 36 |
"v": "urn:schemas-microsoft-com:vml", |
| 37 |
"o": "urn:schemas-microsoft-com:office:office", |
| 38 |
"m": "http://schemas.openxmlformats.org/officeDocument/2006/math", |
| 39 |
"xml": "http://www.w3.org/XML/1998/namespace" |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
class paragraf(): |
| 45 |
|
| 46 |
def __init__(self, element): |
| 47 |
self.element = element |
| 48 |
self.rr = [r for r in docx.iter(element, "w:r")] |
| 49 |
self.tt = [t for r in self.rr for t in docx.iter(r, "w:t")] |
| 50 |
texts = [] |
| 51 |
for t in self.tt: |
| 52 |
if self.get_atrib(t, "xml:space") == "preserve": |
| 53 |
texts.append(t.text) |
| 54 |
else: |
| 55 |
texts.append(t.text.strip()) |
| 56 |
self.txt = "|".join(texts) |
| 57 |
self.mides = [len(t) for t in texts] |
| 58 |
|
| 59 |
def get_atrib(self, element, nom, defecte = None): |
| 60 |
pn = nom.split(":", 1) |
| 61 |
pn = "{%s}%s" % (docx.ns[pn[0]], pn[1]) |
| 62 |
valor = element.get(pn, defecte) |
| 63 |
return valor |
| 64 |
|
| 65 |
|
| 66 |
linia = "" |
| 67 |
while True: |
| 68 |
c = sys.stdin.read(1) |
| 69 |
if not c or c == '\0': |
| 70 |
break |
| 71 |
else: |
| 72 |
linia += c |
| 73 |
linies = [ linia ] |
| 74 |
#sys.stdout.write("#lĂnies: %d" % (len(linies))) |
| 75 |
doc = docx(linies) |
| 76 |
for p in doc.pars: |
| 77 |
print(p.txt) |
| 78 |
sys.stdout.write('\0') |
| 79 |
sys.stdout.flush() |
| 80 |
|