蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

生成并重新读取一份真实 DOCX

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。document_lab.py
document_lab.py34 行
"""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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 document_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a340.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习