如何用Markdown模板批量管理GitHub仓库中的标准化文档?
解决方案:用「结构化内容文件 + 模板引擎」实现批量生成与统一维护
1. 第一步:把DOCX内容提取为结构化的内容文件
先把每个DOCX里的Problem、Options、Recommendation模块内容提取出来,存成YAML格式(易读易编辑),每个知识条目对应一个独立的内容文件,比如knowledge_01.yaml:
# knowledge_01.yaml problem: "从DOCX提取的具体问题描述" options: | - 选项A:xxx - 选项B:yyy - 选项C:zzz recommendation: "从DOCX提取的最终推荐方案"
用Python的python-docx库可以批量提取DOCX内容,示例脚本逻辑:
from docx import Document import yaml import os # 遍历所有DOCX文件 for docx_file in os.listdir("./docx_files"): if not docx_file.endswith(".docx"): continue doc = Document(f"./docx_files/{docx_file}") content = {"problem": "", "options": "", "recommendation": ""} current_section = None # 识别模块标题并提取对应内容 for para in doc.paragraphs: text = para.text.strip() if text == "Problem": current_section = "problem" continue elif text == "Options": current_section = "options" continue elif text == "Recommendation": current_section = "recommendation" continue if current_section and text: content[current_section] += text + "\n" # 保存为YAML文件 yaml_filename = f"./content/{os.path.splitext(docx_file)[0]}.yaml" with open(yaml_filename, "w", encoding="utf-8") as f: yaml.dump(content, f, allow_unicode=True)
2. 第二步:编写统一的Markdown模板
用Jinja2(Python生态常用模板引擎)写一个模板文件template.md.j2,定义最终MD文件的结构:
# {{ filename.replace('.yaml', '') }} ## Problem {{ problem }} ## Options {{ options }} ## Recommendation {{ recommendation }}
后续要调整结构(比如把Recommendation改名为Solution),只需要修改这个模板文件,所有生成的MD文件都会同步更新。
3. 第三步:批量渲染生成Markdown文件
写一个Python脚本,加载模板、遍历所有YAML内容文件,渲染生成最终的MD文件:
from jinja2 import Environment, FileSystemLoader import yaml import os # 加载模板 env = Environment(loader=FileSystemLoader("./")) template = env.get_template("template.md.j2") # 遍历内容文件生成MD for yaml_file in os.listdir("./content"): if not yaml_file.endswith(".yaml"): continue with open(f"./content/{yaml_file}", "r", encoding="utf-8") as f: content = yaml.safe_load(f) # 渲染模板 md_content = template.render(**content, filename=yaml_file) # 保存MD文件 md_filename = f"./output/{os.path.splitext(yaml_file)[0]}.md" with open(md_filename, "w", encoding="utf-8") as f: f.write(md_content)
4. 后续维护
- 调整结构:修改
template.md.j2后重新运行渲染脚本,批量更新所有MD文件。 - 修改内容:直接修改对应的YAML文件,重新渲染即可。
- 新增条目:新增YAML内容文件,运行脚本自动生成对应MD文件。
内容的提问来源于stack exchange,提问作者sOltan
相关产品推荐
相关产品推荐

