test: docx 测试基建(新建/落盘/规则文档快捷构造)
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user