"""Offline LaTeX verification lab for Chapter 08 (latex-figures-tables)."""
import json
import re
VERSION = "CPython 3.12.14 offline LaTeX figure & tabular structure verifier"
def parse_tabular_colspec(spec: str) -> dict:
cols = []
vrules = 0
i = 0
while i < len(spec):
ch = spec[i]
if ch in "lcr":
cols.append(ch)
i += 1
elif ch == "|":
vrules += 1
i += 1
elif ch == "p" and i + 1 < len(spec) and spec[i + 1] == "{":
end = spec.index("}", i + 2)
cols.append(spec[i : end + 1])
i = end + 1
else:
i += 1
return {"columns": cols, "column_count": len(cols), "vertical_rules": vrules}
def case_graphicx_and_figure_float():
doc = r"""
\documentclass{ctexart}
\usepackage{graphicx}
\begin{document}
正弦函数 $y = \sin x$ 的图像如图~\ref{fig:sin} 所示。
\begin{figure}[htbp]
\centering
\includegraphics[width=0.6\textwidth]{sin}
\caption{正弦函数曲线}
\label{fig:sin}
\end{figure}
\end{document}
"""
fig_m = re.search(r"\\begin\{figure\}\[([^\]]+)\](.+?)\\end\{figure\}", doc, re.S)
placement = fig_m.group(1)
body = fig_m.group(2)
inc = re.search(r"\\includegraphics\[([^\]]+)\]\{([^}]+)\}", body)
cap_pos = body.find(r"\caption{")
lbl_pos = body.find(r"\label{")
inc_pos = body.find(r"\includegraphics")
actual = {
"placement_tokens": list(placement),
"valid_standard_floats": all(c in set("htbp!") for c in placement),
"uses_centering": r"\centering" in body,
"image_option": inc.group(1),
"image_name_omits_ext": "." not in inc.group(2),
"caption_below_image_and_before_label": inc_pos < cap_pos < lbl_pos,
"label_prefix": re.search(r"\\label\{([^:]+):", body).group(1),
}
expected = {
"placement_tokens": ["h", "t", "b", "p"],
"valid_standard_floats": True,
"uses_centering": True,
"image_option": r"width=0.6\textwidth",
"image_name_omits_ext": True,
"caption_below_image_and_before_label": True,
"label_prefix": "fig",
}
return {
"name": "graphicx_and_figure_float",
"summary": "检验 figure 浮动位置参数、无扩展名插图、相对版心宽度及“图在下题、先 \\caption 后 \\label”规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_basic_tabular_colspec_and_rows():
doc = r"""
\begin{tabular}{|l|c|r|}
\hline
姓名 & 年龄 & 得分 \\
\hline
张三 & 20 & 92 \\
李四 & 21 & 88 \\
\hline
\end{tabular}
"""
m = re.search(r"\\begin\{tabular\}\{([^}]+)\}(.+?)\\end\{tabular\}", doc, re.S)
col_info = parse_tabular_colspec(m.group(1))
data_lines = [ln.strip() for ln in m.group(2).splitlines() if "&" in ln]
row_widths = [len(ln.rstrip("\\ ").split("&")) for ln in data_lines]
p_col_info = parse_tabular_colspec("lp{2cm}r")
actual = {
"col_info": col_info,
"row_count": len(data_lines),
"all_rows_match_cols": all(w == col_info["column_count"] for w in row_widths),
"p_col_parsed": p_col_info["columns"],
}
expected = {
"col_info": {"columns": ["l", "c", "r"], "column_count": 3, "vertical_rules": 4},
"row_count": 3,
"all_rows_match_cols": True,
"p_col_parsed": ["l", "p{2cm}", "r"],
}
return {
"name": "basic_tabular_colspec_and_rows",
"summary": "解析 tabular 列格式(|l|c|r| 与 p{2cm})及数据行列数一致性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_booktabs_three_line_table():
doc = r"""
\documentclass{ctexart}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{lccc}
\toprule
算法 & 准确率 & 召回率 & F1 \\
\midrule
模型 A & 0.91 & 0.88 & 0.89 \\
模型 B & 0.93 & 0.90 & 0.91 \\
\bottomrule
\end{tabular}
\end{document}
"""
spec = re.search(r"\\begin\{tabular\}\{([^}]+)\}", doc).group(1)
col_info = parse_tabular_colspec(spec)
rules = re.findall(r"\\(toprule|midrule|bottomrule)", doc)
actual = {
"has_booktabs": r"\usepackage{booktabs}" in doc,
"zero_vertical_rules": col_info["vertical_rules"] == 0,
"column_count": col_info["column_count"],
"rule_order": rules,
}
expected = {
"has_booktabs": True,
"zero_vertical_rules": True,
"column_count": 4,
"rule_order": ["toprule", "midrule", "bottomrule"],
}
return {
"name": "booktabs_three_line_table",
"summary": "验证 booktabs 学术三线表零竖线原则及 \\toprule -> \\midrule -> \\bottomrule 顺序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multirow_multicolumn_and_table_float():
doc = r"""
\usepackage{booktabs}
\usepackage{multirow}
\begin{table}[htbp]
\centering
\caption{实验结果对比}
\label{tab:result}
\begin{tabular}{lcc}
\toprule
\multirow{2}{*}{数据集} & \multicolumn{2}{c}{准确率} \\
\cmidrule(lr){2-3}
& 训练集 & 测试集 \\
\midrule
MNIST & 0.99 & 0.98 \\
CIFAR-10 & 0.95 & 0.91 \\
\bottomrule
\end{tabular}
\end{table}
"""
mr = re.search(r"\\multirow\{(\d+)\}\{([^}]+)\}\{([^}]+)\}", doc)
mc = re.search(r"\\multicolumn\{(\d+)\}\{([^}]+)\}\{([^}]+)\}", doc)
cm = re.search(r"\\cmidrule\(([^)]+)\)\{(\d+-\d+)\}", doc)
cap_pos = doc.find(r"\caption{")
tab_pos = doc.find(r"\begin{tabular}")
# Row 1 effective columns: 1 (from multirow cell) + 2 (from multicolumn{2}) = 3
row1_cols = 1 + int(mc.group(1))
spec_cols = parse_tabular_colspec("lcc")["column_count"]
actual = {
"multirow_span_and_text": [int(mr.group(1)), mr.group(3)],
"multicolumn_span_align_text": [int(mc.group(1)), mc.group(2), mc.group(3)],
"cmidrule_trim_range": [cm.group(1), cm.group(2)],
"header_row1_matches_colspec": row1_cols == spec_cols,
"table_caption_above_tabular": cap_pos < tab_pos,
"label_prefix": re.search(r"\\label\{([^:]+):", doc).group(1),
}
expected = {
"multirow_span_and_text": [2, "数据集"],
"multicolumn_span_align_text": [2, "c", "准确率"],
"cmidrule_trim_range": ["lr", "2-3"],
"header_row1_matches_colspec": True,
"table_caption_above_tabular": True,
"label_prefix": "tab",
}
return {
"name": "multirow_multicolumn_and_table_float",
"summary": "检验 \\multirow/\\multicolumn/\\cmidrule(lr){2-3} 双层表头列宽配平与 table 浮动体表题置顶规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_graphicx_and_figure_float(),
case_basic_tabular_colspec_and_rows(),
case_booktabs_three_line_table(),
case_multirow_multicolumn_and_table_float(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。
入口文件:projects/latex-latex-figures-tables-lab/explore-latex-figures-tables.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-latex-figures-tables.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2298.zip
课程关联工程包(登记关联12章) · 含当前章节或实例 · mbskycom202612a2294.zip