From e8771aa797d342d5e15344d0feaa97b0e1af9ce3 Mon Sep 17 00:00:00 2001 From: lhl Date: Mon, 10 Aug 2026 09:21:55 +0800 Subject: [PATCH] =?UTF-8?q?test:=20docx=20=E6=B5=8B=E8=AF=95=E5=9F=BA?= =?UTF-8?q?=E5=BB=BA=EF=BC=88=E6=96=B0=E5=BB=BA/=E8=90=BD=E7=9B=98/?= =?UTF-8?q?=E8=A7=84=E5=88=99=E6=96=87=E6=A1=A3=E5=BF=AB=E6=8D=B7=E6=9E=84?= =?UTF-8?q?=E9=80=A0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/docx_helpers.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 tests/docx_helpers.py diff --git a/tests/docx_helpers.py b/tests/docx_helpers.py new file mode 100644 index 0000000..d7d921d --- /dev/null +++ b/tests/docx_helpers.py @@ -0,0 +1,37 @@ +from docx import Document + + +def new_document() -> Document: + """新建内存 Word 文档(python-docx 默认模板)。""" + return Document() + + +def save_document(tmp_path, doc: Document) -> str: + """落盘到 tmp_path 并返回路径字符串。""" + path = tmp_path / "source.docx" + doc.save(path) + return str(path) + + +def make_rule_doc(tmp_path, lines: list[tuple[str, str]]) -> str: + """快捷构造规则文档。 + + lines 每项为 (样式标识, 文本): + ("H1", "1. 章") / ("H2", "1.1 節") / ("H3", ...) → Heading 层级 + ("list", "・項目") → List Bullet 样式段落 + ("", "普通段落") → Normal 段落 + 返回落盘路径字符串。 + """ + doc = new_document() + for kind, text in lines: + if kind == "H1": + doc.add_heading(text, level=1) + elif kind == "H2": + doc.add_heading(text, level=2) + elif kind == "H3": + doc.add_heading(text, level=3) + elif kind == "list": + doc.add_paragraph(text, style="List Bullet") + else: + doc.add_paragraph(text) + return save_document(tmp_path, doc)