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

离线解析首个 LaTeX 文档结构、网页数学片段与环境嵌套平衡

PYTHONWindows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。explore-tutorial.py
explore-tutorial.py213 行
"""Offline LaTeX verification lab for Chapter 01 (tutorial)."""
import json
import re

VERSION = "CPython 3.12.14 offline LaTeX syntax & structure verifier"


def parse_latex_document(src: str) -> dict:
    clean = re.sub(r"(?<!\\)%.*", "", src)
    docclass = re.search(r"\\documentclass(?:\[([^\]]*)\])?\{([^}]+)\}", clean)
    begin_m = re.search(r"\\begin\{document\}", clean)
    end_m = re.search(r"\\end\{document\}", clean)
    preamble = clean[: begin_m.start()] if begin_m else ""
    body = clean[begin_m.end() : end_m.start()] if (begin_m and end_m) else ""
    meta = {}
    for field in ("title", "author", "date"):
        m = re.search(rf"\\{field}\{{([^}}]*)\}}", preamble)
        if m:
            meta[field] = m.group(1).strip()
    sections = re.findall(r"\\section\*?\{([^}]+)\}", body)
    inline_dollar = re.findall(r"(?<!\\)\$(?!\$)(.+?)(?<!\\)\$", body, re.S)
    display_bracket = re.findall(r"\\\[(.+?)\\\]", body, re.S)
    return {
        "document_class": docclass.group(2) if docclass else None,
        "has_preamble_and_body": bool(begin_m and end_m and begin_m.start() < end_m.start()),
        "meta_fields": sorted(meta.keys()),
        "has_maketitle": r"\maketitle" in body,
        "sections": sections,
        "inline_math_count": len(inline_dollar),
        "display_math_count": len(display_bracket),
    }


def case_basic_latex_document_structure():
    sample = r"""
\documentclass{article} % 文档类
\title{我的第一个 LaTeX 文档} % 标题
\author{林远} % 作者
\date{\today} % 日期

\begin{document}
\maketitle % 生成标题

\section{引言} % 章节
这是我的第一个 LaTeX 文档!\\ % 换行
这是一个简单的段落。

\section{数学公式}
这是一个行内公式:$E = mc^2$。\\ % 行内公式
这是一个行间公式:
\[
\int_a^b f(x) \, dx
\]
\end{document}
"""
    actual = parse_latex_document(sample)
    expected = {
        "document_class": "article",
        "has_preamble_and_body": True,
        "meta_fields": ["author", "date", "title"],
        "has_maketitle": True,
        "sections": ["引言", "数学公式"],
        "inline_math_count": 1,
        "display_math_count": 1,
    }
    return {
        "name": "basic_latex_document_structure",
        "summary": "解析首个 LaTeX 文档的文档类、导言区元信息、正文区边界、章节与行内/行间数学公式",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_web_embedded_math_fragments():
    html_snippet = r"""
<!-- 行内公式 -->
<p>行内公式:\( E = mc^2 \)</p>
<!-- 行间公式 -->
<p>行间公式:\[ \int_a^b f(x) \, dx \]</p>
<!-- 矩阵 -->
<p>矩阵:
\[
\begin{pmatrix}
  1 & 2 \\
  3 & 4
\end{pmatrix}
\]
</p>
<!-- 方程组 -->
<p>方程组:
\[
\begin{cases}
  x + y = 5 \\
  2x - y = 1
\end{cases}
\]
</p>
"""
    inline_paren = [m.strip() for m in re.findall(r"\\\((.+?)\\\)", html_snippet, re.S)]
    display_blocks = [m.strip() for m in re.findall(r"\\\[(.+?)\\\]", html_snippet, re.S)]
    envs = re.findall(r"\\begin\{([^}]+)\}", html_snippet)
    end_envs = re.findall(r"\\end\{([^}]+)\}", html_snippet)

    actual = {
        "inline_paren_count": len(inline_paren),
        "inline_first": inline_paren[0],
        "display_block_count": len(display_blocks),
        "environments": envs,
        "environments_balanced": envs == end_envs,
    }
    expected = {
        "inline_paren_count": 1,
        "inline_first": "E = mc^2",
        "display_block_count": 3,
        "environments": ["pmatrix", "cases"],
        "environments_balanced": True,
    }
    return {
        "name": "web_embedded_math_fragments",
        "summary": "校验网页内嵌 LaTeX 数学片段中的行内 \\(...\\)、行间 \\[...\\]、pmatrix 矩阵与 cases 方程组",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_audience_and_origin_profile():
    profile = {
        "base_engine": "TeX",
        "tex_author": "Donald Knuth",
        "latex_author": "Leslie Lamport",
        "pronunciations": ["Lay-tech", "Lah-tech"],
        "roles": ["学生", "研究人员", "工程师", "出版从业者"],
        "needs": [
            "复杂公式、图表与代码排版",
            "高排版质量要求",
            "长文档与技术文档维护",
            "提升专业写作效率",
        ],
    }
    actual = {
        "base_engine": profile["base_engine"],
        "latex_author": profile["latex_author"],
        "pronunciation_count": len(profile["pronunciations"]),
        "role_count": len(profile["roles"]),
        "need_count": len(profile["needs"]),
    }
    expected = {
        "base_engine": "TeX",
        "latex_author": "Leslie Lamport",
        "pronunciation_count": 2,
        "role_count": 4,
        "need_count": 4,
    }
    return {
        "name": "audience_and_origin_profile",
        "summary": "核对 LaTeX 发音、TeX 底层与 Leslie Lamport 渊源及四类读者与核心需求模型",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_environment_balance_validator():
    def check_balance(src: str) -> tuple[bool, str]:
        stack = []
        for kind, name in re.findall(r"\\(begin|end)\{([^}]+)\}", src):
            if kind == "begin":
                stack.append(name)
            else:
                if not stack or stack[-1] != name:
                    return False, f"mismatched_end:{name}"
                stack.pop()
        if stack:
            return False, f"unclosed:{stack[-1]}"
        return True, "ok"

    good = r"\begin{document}\begin{pmatrix}1 & 2 \\ 3 & 4\end{pmatrix}\end{document}"
    bad_unclosed = r"\begin{document}\begin{cases}x+y=5\end{document}"
    bad_extra = r"\begin{document}hello\end{document}\end{itemize}"
    actual = {
        "good": list(check_balance(good)),
        "bad_unclosed": list(check_balance(bad_unclosed)),
        "bad_extra": list(check_balance(bad_extra)),
    }
    expected = {
        "good": [True, "ok"],
        "bad_unclosed": [False, "mismatched_end:document"],
        "bad_extra": [False, "mismatched_end:itemize"],
    }
    return {
        "name": "environment_balance_validator",
        "summary": "离线检验 LaTeX \\begin{...} 与 \\end{...} 环境嵌套的闭合与错配检测",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_basic_latex_document_structure(),
        case_web_embedded_math_fragments(),
        case_audience_and_origin_profile(),
        case_environment_balance_validator(),
    ]
    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-tutorial-lab/explore-tutorial.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LaTeX

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

下载课程关联工程包:LaTeX

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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