Files
umed/web/scripts/extract-docx.py
T
2026-07-09 14:35:32 +08:00

24 lines
639 B
Python

import zipfile
import xml.etree.ElementTree as ET
import sys
path = sys.argv[1]
W = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
with zipfile.ZipFile(path) as z:
root = ET.fromstring(z.read('word/document.xml'))
out = sys.argv[2] if len(sys.argv) > 2 else None
lines = []
for i, p in enumerate(root.iter(f'{W}p')):
texts = [t.text or '' for t in p.iter(f'{W}t')]
line = ''.join(texts).strip()
if line:
lines.append(f'{i + 1}|{line}')
text = '\n'.join(lines)
if out:
with open(out, 'w', encoding='utf-8') as f:
f.write(text)
else:
sys.stdout.buffer.write(text.encode('utf-8'))