track_changes_bold_postprocess.py
Helper script for the track_changes workflow.
import sys, copy
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def fix_bold(path):
d = Document(path)
for p in d.paragraphs:
for r in list(p._p.iter(qn('w:r'))):
t, dt = r.find(qn('w:t')), r.find(qn('w:delText'))
e = t if t is not None else dt
if e is None or not e.text or '**' not in e.text: continue
tag = 'w:delText' if dt is not None and t is None else 'w:t'
pts = e.text.split('**')
if len(pts) <= 1: continue
par, idx = r.getparent(), list(r.getparent()).index(r)
ex_rpr = r.find(qn('w:rPr'))
bold = False
for i, pt in enumerate(pts):
if i > 0: bold = not bold
if not pt: continue
nr, rpr = OxmlElement('w:r'), OxmlElement('w:rPr')
if ex_rpr is not None:
for c in ex_rpr: rpr.append(copy.deepcopy(c))
if bold: rpr.append(OxmlElement('w:b'))
if len(rpr) > 0: nr.append(rpr)
nt = OxmlElement(tag)
nt.set(qn('xml:space'), 'preserve')
nt.text = pt
nr.append(nt)
par.insert(idx + i, nr)
par.remove(r)
d.save(path)
if __name__ == '__main__': fix_bold(sys.argv[1])