docx_dump.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # -*- coding: utf-8 -*-
  2. """把生成的 docx 按正文顺序导出成纯文本,用于人工校对(只读,不改文档)。"""
  3. import sys
  4. import docx
  5. from docx.table import Table
  6. from docx.text.paragraph import Paragraph
  7. def main(path, out_path):
  8. d = docx.Document(path)
  9. lines = []
  10. for child in d.element.body.iterchildren():
  11. tag = child.tag.split("}")[-1]
  12. if tag == "p":
  13. par = Paragraph(child, d)
  14. if par.text.strip():
  15. lines.append("[%s] %s" % (par.style.name, par.text))
  16. elif tag == "tbl":
  17. t = Table(child, d)
  18. lines.append("<表格 %d 行 x %d 列>" % (len(t.rows), len(t.columns)))
  19. for r in t.rows:
  20. lines.append(" | " + " | ".join(c.text.replace("\n", " ") for c in r.cells))
  21. text = "\n".join(lines)
  22. with open(out_path, "w", encoding="utf-8") as fh:
  23. fh.write(text)
  24. bad = [ln for ln in lines if "**" in ln]
  25. bt = [ln for ln in lines if "`" in ln]
  26. print("lines=%d chars=%d bold_markup=%d backtick=%d" % (len(lines), len(text), len(bad), len(bt)))
  27. for ln in bad[:5] + bt[:5]:
  28. print(" !", ln[:120])
  29. return 0
  30. if __name__ == "__main__":
  31. raise SystemExit(main(sys.argv[1], sys.argv[2]))