- textbook/main.c:单文件控制台程序(约 400 行、13 个函数),覆盖项目一~九知识点 - textbook/项目十-章节正文.md:章节正文源稿 - textbook/figs:8 张控制台运行结果截图(真实回显) - textbook/tools:截图与 docx 生成脚本 - 10.16C语言程序设计教材初稿 - 项目十.docx:按原稿样式生成的综合章节(28 页)
406 lines
15 KiB
Python
406 lines
15 KiB
Python
"""Build the 项目十 chapter DOCX using the original textbook as a style template."""
|
||
import os
|
||
import re
|
||
|
||
from docx import Document
|
||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||
from docx.oxml import OxmlElement
|
||
from docx.oxml.ns import qn
|
||
from docx.shared import Inches, Pt, RGBColor
|
||
|
||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # textbook/
|
||
PROJECT_DIR = os.path.dirname(BASE_DIR) # 仓库根目录
|
||
FIG_DIR = os.path.join(BASE_DIR, "figs")
|
||
SRC_DOCX = os.path.join(PROJECT_DIR, "10.16C语言程序设计教材初稿 - 项目版.docx")
|
||
OUT_DOCX = os.path.join(PROJECT_DIR, "10.16C语言程序设计教材初稿 - 项目十.docx")
|
||
MD = os.path.join(BASE_DIR, "项目十-章节正文.md")
|
||
|
||
FIG_CAPTIONS = {
|
||
"10-1": ("fig10-1.png", "设备台账运行结果"),
|
||
"10-2": ("fig10-2.png", "主菜单运行结果"),
|
||
"10-3": ("fig10-3.png", "设备控制运行结果"),
|
||
"10-4": ("fig10-4.png", "状态标志位操作运行结果"),
|
||
"10-5": ("fig10-5.png", "场景联动运行结果"),
|
||
"10-6": ("fig10-6.png", "统计报表运行结果"),
|
||
"10-7": ("fig10-7.png", "配置保存与加载运行结果"),
|
||
"10-8": ("fig10-8.png", "运行日志查看结果"),
|
||
}
|
||
|
||
ASSESS_ROWS = [
|
||
("一、知识掌握(40 分)", "一、知识掌握(40 分)", "", "", ""),
|
||
("结构体与结构体数组", "能正确定义设备结构体、声明结构体数组并初始化", "", "", ""),
|
||
("菜单与分支", "能写出 do-while + switch 菜单框架,正确使用 break、default", "", "", ""),
|
||
("数组与统计", "能完成求和、均值、最值、分类计数的代码编写", "", "", ""),
|
||
("指针出参", "能说明“为什么统计函数要用指针参数”,并正确调用", "", "", ""),
|
||
("位运算", "能写出置位、清零、取反、取位、循环移位的表达式", "", "", ""),
|
||
("文件操作", "能正确选择 \"r\"/\"w\"/\"a\" 模式,并检查 fopen 返回值", "", "", ""),
|
||
("二、技能应用(40 分)", "二、技能应用(40 分)", "", "", ""),
|
||
("系统集成", "九个菜单项全部可用,功能之间数据一致", "", "", ""),
|
||
("数据持久化", "保存后重启能完整恢复台账", "", "", ""),
|
||
("异常处理", "非法编号、越界参数、文件缺失均有提示且不崩溃", "", "", ""),
|
||
("运行验证", "能独立完成“改参数→保存→重启→加载”的全流程演示", "", "", ""),
|
||
("三、学习素养(20 分)", "三、学习素养(20 分)", "", "", ""),
|
||
("代码规范", "缩进统一、命名清晰、关键语句有中文注释", "", "", ""),
|
||
("调试能力", "能定位并修正至少一处自己引入的逻辑错误", "", "", ""),
|
||
("文档习惯", "实训报告包含功能清单、测试用例与运行截图", "", "", ""),
|
||
("总分", "自评 ______ 互评 ______ 教师 ______", "", "", ""),
|
||
]
|
||
|
||
|
||
def clear_body(doc):
|
||
body = doc.element.body
|
||
sect = body.find(qn("w:sectPr"))
|
||
for child in list(body):
|
||
if child is sect:
|
||
continue
|
||
body.remove(child)
|
||
|
||
|
||
|
||
PPR_AFTER_SNAP = {"spacing", "ind", "contextualSpacing", "mirrorIndents",
|
||
"suppressOverlap", "jc", "textDirection", "textAlignment",
|
||
"textboxTightWrap", "outlineLvl", "divId", "cnfStyle",
|
||
"rPr", "sectPr", "pPrChange"}
|
||
|
||
|
||
def no_grid(par):
|
||
"""Disable snap-to-grid so line spacing is not doubled by the document grid."""
|
||
pPr = par._p.get_or_add_pPr()
|
||
if pPr.find(qn("w:snapToGrid")) is not None:
|
||
return par
|
||
el = OxmlElement("w:snapToGrid")
|
||
el.set(qn("w:val"), "0")
|
||
for child in list(pPr):
|
||
name = child.tag.split("}")[1]
|
||
if name in PPR_AFTER_SNAP:
|
||
child.addprevious(el)
|
||
return par
|
||
pPr.append(el)
|
||
return par
|
||
|
||
def add_runs(par, text, bold=False):
|
||
"""Add text honouring **bold** and `code` spans."""
|
||
for tok in re.split(r"(\*\*.+?\*\*|`[^`]+`)", text):
|
||
if not tok:
|
||
continue
|
||
if tok.startswith("**") and tok.endswith("**") and len(tok) > 4:
|
||
run = par.add_run(tok[2:-2])
|
||
run.bold = True
|
||
elif tok.startswith("`") and tok.endswith("`") and len(tok) > 2:
|
||
run = par.add_run(tok[1:-1])
|
||
run.font.name = "Consolas"
|
||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||
run.font.size = Pt(10)
|
||
else:
|
||
run = par.add_run(tok)
|
||
run.bold = bold
|
||
run._element.set(qn("xml:space"), "preserve")
|
||
|
||
|
||
def body_par(doc, text, indent=True):
|
||
if text.startswith("- "):
|
||
p = doc.add_paragraph(style="Normal")
|
||
pf = p.paragraph_format
|
||
pf.left_indent = Inches(0.32)
|
||
pf.first_line_indent = Inches(-0.18)
|
||
add_runs(p, "· " + text[2:])
|
||
return p
|
||
p = doc.add_paragraph(style="Normal")
|
||
add_runs(p, text)
|
||
return p
|
||
|
||
|
||
def caption_par(doc, text, bold=True):
|
||
p = doc.add_paragraph(style="Normal")
|
||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
p.paragraph_format.keep_with_next = True
|
||
for run in []:
|
||
pass
|
||
no_grid(p)
|
||
r = p.add_run(text)
|
||
r.bold = bold
|
||
r.font.name = "Times New Roman"
|
||
r._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||
return p
|
||
|
||
|
||
|
||
def harden_table(table, header=True):
|
||
for ri, row in enumerate(table.rows):
|
||
trPr = row._tr.get_or_add_trPr()
|
||
if trPr.find(qn("w:cantSplit")) is None:
|
||
trPr.append(OxmlElement("w:cantSplit"))
|
||
if header and ri == 0 and trPr.find(qn("w:tblHeader")) is None:
|
||
trPr.append(OxmlElement("w:tblHeader"))
|
||
|
||
def add_table(doc, rows, header=True):
|
||
cols = max(len(r) for r in rows)
|
||
table = doc.add_table(rows=len(rows), cols=cols)
|
||
table.style = "Table Grid"
|
||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||
for ri, row in enumerate(rows):
|
||
for ci in range(cols):
|
||
cell = table.cell(ri, ci)
|
||
text = row[ci] if ci < len(row) else ""
|
||
text = text.replace("`", "").replace("**", "")
|
||
par = cell.paragraphs[0]
|
||
par.alignment = WD_ALIGN_PARAGRAPH.CENTER if (ri == 0 or header and ri == 0) else WD_ALIGN_PARAGRAPH.LEFT
|
||
run = par.add_run(text)
|
||
run.font.size = Pt(10)
|
||
run.font.name = "宋体"
|
||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||
if ri == 0 and header:
|
||
run.bold = True
|
||
harden_table(table, header=header)
|
||
doc.add_paragraph(style="Normal")
|
||
return table
|
||
|
||
|
||
def add_assessment(doc):
|
||
cols = 5
|
||
table = doc.add_table(rows=len(ASSESS_ROWS) + 2, cols=cols)
|
||
table.style = "Table Grid"
|
||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||
|
||
head = table.cell(0, 0).merge(table.cell(0, 4))
|
||
head.paragraphs[0].add_run("姓名:____________ 所在小组:____________ 日期:____________")
|
||
head.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
|
||
titles = ["评价维度", "评价标准", "学生自评(25%)", "学生互评(25%)", "教师评价(50%)"]
|
||
for ci, t in enumerate(titles):
|
||
cell = table.cell(1, ci)
|
||
run = cell.paragraphs[0].add_run(t)
|
||
run.bold = True
|
||
run.font.size = Pt(8.5)
|
||
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
|
||
for ri, row in enumerate(ASSESS_ROWS, start=2):
|
||
section = row[1] == row[0] or row[0] in ("总分",)
|
||
if row[0].startswith(("一、", "二、", "三、")):
|
||
merged = table.cell(ri, 0).merge(table.cell(ri, 4))
|
||
run = merged.paragraphs[0].add_run(row[0])
|
||
run.bold = True
|
||
run.font.size = Pt(8.5)
|
||
merged.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||
continue
|
||
if row[0] == "总分":
|
||
c0 = table.cell(ri, 0)
|
||
c1 = table.cell(ri, 1).merge(table.cell(ri, 4))
|
||
for cell, txt, bold in ((c0, "总分", True), (c1, row[1], False)):
|
||
run = cell.paragraphs[0].add_run(txt)
|
||
run.bold = bold
|
||
run.font.size = Pt(8.5)
|
||
continue
|
||
for ci in range(cols):
|
||
cell = table.cell(ri, ci)
|
||
txt = row[ci] if ci < len(row) else ""
|
||
run = cell.paragraphs[0].add_run(txt)
|
||
run.font.size = Pt(8.5)
|
||
if ci == 0:
|
||
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
widths = [Inches(1.15), Inches(2.15), Inches(0.85), Inches(0.85), Inches(0.85)]
|
||
table.autofit = False
|
||
for idx, w in enumerate(widths):
|
||
table.columns[idx].width = w
|
||
for row in table.rows:
|
||
for idx, w in enumerate(widths):
|
||
try:
|
||
row.cells[idx].width = w
|
||
except IndexError:
|
||
pass
|
||
harden_table(table, header=True)
|
||
doc.add_paragraph(style="Normal")
|
||
|
||
|
||
def add_figure(doc, case_no):
|
||
fname, cap = FIG_CAPTIONS[case_no]
|
||
path = os.path.join(FIG_DIR, fname)
|
||
from PIL import Image
|
||
w, h = Image.open(path).size
|
||
width = 4.2
|
||
height = width * h / w
|
||
if height > 7.2:
|
||
height = 7.2
|
||
width = height * w / h
|
||
p = doc.add_paragraph(style="Normal")
|
||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
p.paragraph_format.keep_with_next = True
|
||
p.add_run().add_picture(path, width=Inches(width))
|
||
caption_par(doc, f"图{case_no} {cap}")
|
||
|
||
|
||
def add_code_line(doc, text):
|
||
p = doc.add_paragraph(style="HTML Preformatted")
|
||
pf = p.paragraph_format
|
||
pf.first_line_indent = Inches(0)
|
||
pf.space_before = Pt(0)
|
||
pf.space_after = Pt(0)
|
||
no_grid(p)
|
||
run = p.add_run(text if text.strip() else " ")
|
||
run.font.name = "Consolas"
|
||
run.font.size = Pt(8.5)
|
||
run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
|
||
run._element.set(qn("xml:space"), "preserve")
|
||
return p
|
||
|
||
|
||
def parse_table_row(line):
|
||
cells = re.split(r"(?<!\\)\|", line.strip().strip("|"))
|
||
return [c.strip().replace("\\|", "|") for c in cells]
|
||
|
||
|
||
def build():
|
||
doc = Document(SRC_DOCX)
|
||
clear_body(doc)
|
||
doc.styles["Heading 2"].font.size = Pt(15)
|
||
|
||
lines = open(MD, encoding="utf-8").read().splitlines()
|
||
i = 0
|
||
current_case = None
|
||
in_assessment = False
|
||
|
||
while i < len(lines):
|
||
line = lines[i]
|
||
stripped = line.strip()
|
||
|
||
if stripped.startswith("```"):
|
||
lang = stripped[3:].strip()
|
||
i += 1
|
||
block = []
|
||
while i < len(lines) and not lines[i].strip().startswith("```"):
|
||
block.append(lines[i])
|
||
i += 1
|
||
i += 1
|
||
if lang == "c":
|
||
for code_line in block:
|
||
add_code_line(doc, code_line)
|
||
elif lang == "text":
|
||
block_text = "\n".join(block)
|
||
is_run_result = ("请选择功能" in block_text) or (current_case == "10-1")
|
||
if current_case in FIG_CAPTIONS and is_run_result:
|
||
add_figure(doc, current_case)
|
||
else:
|
||
for code_line in block:
|
||
add_code_line(doc, code_line)
|
||
continue
|
||
|
||
if stripped.startswith("#### "):
|
||
title = stripped[5:].strip()
|
||
m = re.search(r"案例\s*(\d+-\d+)", title)
|
||
current_case = m.group(1) if m else None
|
||
doc.add_paragraph(title, style="Heading 4")
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith("## "):
|
||
title = stripped[3:].strip()
|
||
if title.startswith("任务"):
|
||
h2 = doc.add_paragraph(title, style="Heading 2")
|
||
h2.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
h2.paragraph_format.first_line_indent = Inches(0)
|
||
no_grid(h2)
|
||
elif title.startswith("过程性考核"):
|
||
in_assessment = True
|
||
doc.add_paragraph(title, style="项目引入")
|
||
add_assessment(doc)
|
||
else:
|
||
in_assessment = False
|
||
doc.add_paragraph(title, style="项目引入")
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith("# "):
|
||
h = doc.add_paragraph(stripped[2:].strip(), style="Heading 1")
|
||
h.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||
h.paragraph_format.first_line_indent = Inches(0)
|
||
h.paragraph_format.line_spacing = 1.0
|
||
h.paragraph_format.space_before = Pt(12)
|
||
h.paragraph_format.space_after = Pt(12)
|
||
no_grid(h)
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith("### "):
|
||
doc.add_paragraph(stripped[4:].strip(), style="项目引入")
|
||
i += 1
|
||
continue
|
||
|
||
if in_assessment:
|
||
# skip markdown tables of the assessment section; built programmatically
|
||
if stripped.startswith("|") or stripped == "":
|
||
i += 1
|
||
continue
|
||
if stripped.startswith("## "):
|
||
in_assessment = False
|
||
else:
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith("|"):
|
||
rows = []
|
||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||
raw = lines[i].strip()
|
||
if not re.match(r"^\|[\s\-:|]+\|$", raw):
|
||
rows.append(parse_table_row(raw))
|
||
i += 1
|
||
if rows:
|
||
add_table(doc, rows)
|
||
continue
|
||
|
||
if stripped.startswith("**表"):
|
||
caption_par(doc, stripped.strip("*").strip())
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith(">"):
|
||
quote = []
|
||
while i < len(lines) and lines[i].strip().startswith(">"):
|
||
quote.append(lines[i].strip().lstrip(">").strip())
|
||
i += 1
|
||
quote = [q for q in quote if q]
|
||
if quote:
|
||
first = quote[0]
|
||
if first.startswith("思政点睛"):
|
||
doc.add_paragraph(first.replace("**", ""), style="项目引入")
|
||
for extra in quote[1:]:
|
||
body_par(doc, extra.replace("**", ""))
|
||
else:
|
||
for extra in quote:
|
||
body_par(doc, extra)
|
||
continue
|
||
|
||
if stripped == "":
|
||
i += 1
|
||
continue
|
||
|
||
if stripped.startswith("---"):
|
||
i += 1
|
||
continue
|
||
|
||
body_par(doc, stripped)
|
||
i += 1
|
||
|
||
# 表 10-1 列宽微调,避免首列过窄
|
||
for t in doc.tables:
|
||
if len(t.columns) == 4 and t.rows[0].cells[0].text.strip() == "菜单项":
|
||
widths = [Inches(1.25), Inches(1.75), Inches(1.75), Inches(0.95)]
|
||
t.autofit = False
|
||
for idx, w in enumerate(widths):
|
||
t.columns[idx].width = w
|
||
for row in t.rows:
|
||
for idx, w in enumerate(widths):
|
||
row.cells[idx].width = w
|
||
tblW = t._tbl.tblPr.find(qn("w:tblW"))
|
||
if tblW is not None:
|
||
tblW.set(qn("w:type"), "dxa")
|
||
tblW.set(qn("w:w"), str(int(sum(x.inches for x in widths) * 1440)))
|
||
break
|
||
|
||
doc.save(OUT_DOCX)
|
||
print("saved", OUT_DOCX)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
build()
|