kboss/f/web-kboss/scripts/extract_agreement.py
2026-08-04 17:35:35 +08:00

43 lines
1.4 KiB
Python

import json
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
docx = Path(r'd:\电脑管家迁移文件\xwechat_files\wxid_wfmw9gfr2p9u22_fea0\msg\attach\ca2d7449434be57a2cd16ff8c9e33d13\2026-08\Rec\b548997303412ca6\F\0\开元云用户协议- TY20260729.docx')
W = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
def run_bold(run):
rpr = run.find('w:rPr', ns)
if rpr is None:
return False
bold = rpr.find('w:b', ns)
if bold is None:
return False
val = bold.get(f'{W}val')
return val not in ('0', 'false')
with zipfile.ZipFile(docx) as zf:
root = ET.fromstring(zf.read('word/document.xml'))
paragraphs = []
for paragraph in root.iter(f'{W}p'):
parts = []
for run in paragraph.iter(f'{W}r'):
text = ''.join(t.text or '' for t in run.iter(f'{W}t'))
if not text:
continue
if run_bold(run):
parts.append(f'<strong>{text}</strong>')
else:
parts.append(text)
line = ''.join(parts).strip()
if line:
paragraphs.append(line)
out = Path(__file__).resolve().parents[1] / 'tmp_user_agreement.json'
out.write_text(json.dumps(paragraphs, ensure_ascii=False, indent=2), encoding='utf-8')
print(f'Wrote {len(paragraphs)} paragraphs to {out}')