"""Create a Markdown outline and a genuine Word document from the same plan."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
from docx import Document, __version__
def create_report(output):
if output.suffix.lower() != ".docx":
raise ValueError("output must end in .docx")
title = "Pilot plan"
checklist = ["Inventory pilot", "Review variance"]
outline = output.with_suffix(".md")
outline.write_text(f"# {title}\n\n" + "".join(f"- {item}\n" for item in checklist), encoding="utf8")
document = Document()
document.add_heading(title, level=1)
for item in checklist:
document.add_paragraph(item, style="List Bullet")
document.save(output)
reopened = Document(output)
return dict(version=__version__, markdown_suffix=outline.suffix, docx_suffix=output.suffix,
sha256=sha256(output.read_bytes()).hexdigest(), title=reopened.paragraphs[0].text,
checklist=[paragraph.text for paragraph in reopened.paragraphs[1:]])
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
print(json.dumps(create_report(parser.parse_args().output), ensure_ascii=False))
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-foundations/document_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
document_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a340.zip