| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- # -*- coding: utf-8 -*-
- """Adjust front matter: drop 文档控制, rename 更改记录, page breaks."""
- from __future__ import annotations
- import shutil
- import tempfile
- from pathlib import Path
- from docx import Document
- from docx.enum.text import WD_BREAK
- from docx.oxml import OxmlElement
- from docx.text.paragraph import Paragraph
- BASE = Path(
- r"C:\Users\skygu\OneDrive\Projects\AIDOP\项目\项目管理\产互联项目管理\交付文档"
- )
- def remove_paragraph(p: Paragraph) -> None:
- p._element.getparent().remove(p._element)
- def clear_page_breaks(p: Paragraph) -> None:
- for br in p._element.findall(".//{http://schemas.openxmlformats.org/wordprocessingml/2006/main}br"):
- br.getparent().remove(br)
- def ensure_page_break_before(p: Paragraph) -> None:
- clear_page_breaks(p)
- text = p.text
- p.text = ""
- br_run = p.add_run()
- br_run.add_break(WD_BREAK.PAGE)
- if text:
- p.add_run(text)
- def adjust_file(path: Path) -> None:
- work = path
- tmp_path = None
- try:
- doc = Document(path)
- except PermissionError:
- tmp_path = Path(tempfile.gettempdir()) / f"docfix_{path.name}"
- shutil.copy2(path, tmp_path)
- work = tmp_path
- doc = Document(work)
- removed_control = False
- renamed = False
- version_break = False
- toc_break = False
- for p in list(doc.paragraphs):
- if p.text.strip() == "文档控制":
- remove_paragraph(p)
- removed_control = True
- for p in doc.paragraphs:
- if p.text.strip() == "更改记录":
- p.text = "版本记录"
- renamed = True
- break
- for p in doc.paragraphs:
- if p.text.strip() == "版本记录":
- ensure_page_break_before(p)
- version_break = True
- break
- for p in doc.paragraphs:
- if p.text.strip() == "目录":
- ensure_page_break_before(p)
- toc_break = True
- break
- if not renamed and not any(p.text.strip() == "版本记录" for p in doc.paragraphs):
- raise RuntimeError(f"未找到「版本记录」: {path.name}")
- if not version_break:
- raise RuntimeError(f"未找到「版本记录」: {path.name}")
- if not toc_break:
- raise RuntimeError(f"未找到「目录」: {path.name}")
- doc.save(work)
- if tmp_path is not None:
- try:
- shutil.copy2(work, path)
- tmp_path.unlink(missing_ok=True)
- except PermissionError:
- print(f" !! {path.name} 被占用,已写入: {work}")
- return
- print(
- f"{path.name}: 删文档控制={'Y' if removed_control else 'N'} "
- f"版本记录分页=Y 目录分页=Y"
- )
- def iter_delivery_docx():
- for module in ["S0", "S1", "S2", "S3", "S4"]:
- mod_dir = BASE / module
- if not mod_dir.is_dir():
- continue
- for path in sorted(mod_dir.rglob("*.docx")):
- if not path.name.startswith("~$"):
- yield path
- def main() -> None:
- for path in iter_delivery_docx():
- adjust_file(path)
- if __name__ == "__main__":
- main()
|