Files
MathNotesVersion2/.workbuddy/tools/md2pdf/gen_crosslinks.py
T
Yimu 5b36ef082c 无穷级数点7:重写完成并按知识点拆成三册(08 / 08b / 08c)
原有 7.1—7.3 只有骨架(公式 + 一句结论),看不懂;这一轮按
「从哪来 → 公式 → 走一遍 → 怎么不写错」逐节展开,单文件达 2.7 万字符,
超 1.3 万上限一倍,故按三个知识点拆册(知识点编号与题号不变):

- 08-点7-傅里叶级数.md(10184):7.1 系数公式,6 个小节
  (泰勒对照 → 三角函数系正交性 → 系数即投影 → x^2 走一遍 →
  区间换算两齿轮 → 分部积分流水线与六个失分点),题 1
- 08b-点7-狄利克雷定理与和函数.md(8311):7.2,6 个小节
  (f/~f/S 三对象 → 左右极限平均 → 狄利克雷条件 → 方波六点 →
  取点三步法 → 只有三类点要查),题 2、题 3
- 08c-点7-正弦与余弦级数.md(10567):7.3,7 个小节
  (为何非延拓 → 两套系数与因子 2 → 选延拓 → 偶部/奇部与情形 A/B/C →
  端点行为 → 凑数项级数四步 → 四条失分点),题 4、题 5

gen_crosslinks.py:点文件匹配改为 `NN[x]-点`,题号标签从文件名取点号
(原先按排序推点号,插入 08b/08c 后 09-点8 会被标成"点 10")。

同步:讲 README 文件清单拆三行 + 版本记录;总览 26→27 个知识点、
注明点 7 分三册;两处模拟卷考点手册的 §7.2 链接改指 08b。

校验:check_md_links 245 条 0 异常(两处模拟卷各 102 条 0 异常);
fix_gitea_math 修 52 处收尾缺空格后归零;19 处「加粗以公式收尾」改句式
(脚本补空格反而让星号外露)、3 个含公式的标题改为纯文字。
2026-11-11 13:23:58 +08:00

280 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""线性代数各讲:题目级双向链接 + 盘点 §0.4 反查表 自动生成。
单一数据源 = 点文件里的题目标题。规则:
点文件 02..09-*.md,题目标题 `### 题 N · X.Y:短标题(★★☆)`
X.Y = 该题对应的盘点章节编号
盘点 `### X.Y 章节名`(章节名不含公式,保证锚点稳定)
速查卡 每个 `## ` 标题下一行 `<!-- KP: X.Y, X.Z -->` 声明覆盖的知识点
本脚本做两件事(幂等,可反复跑):
1. 在每道题末尾注入/更新 `> **关联**` 行:
盘点 §X.Y | 上游(同章节、靠前点文件的题)| 下游(靠后的)| 速查
2. 用 `<!-- AUTO:KP -->` 与 `<!-- /AUTO:KP -->` 之间生成盘点 §0.4 表
用法:
python gen_crosslinks.py <讲目录> [--check]
"""
import os
import re
import sys
def anchor(title):
out = []
for ch in title.lower():
if ch.isalnum() or ch == '_':
out.append(ch)
elif ch in ' \t':
out.append('-')
return ''.join(out)
def read(p):
with open(p, encoding='utf-8', newline='') as f:
return f.read().replace('\r\n', '\n')
def write(p, s):
with open(p, 'w', encoding='utf-8', newline='\n') as f:
f.write(s)
def scan_point_file(path):
"""返回 [(kp, no, title_core, full_heading, level_star)]"""
txt = read(path)
out = []
for m in re.finditer(r'^### 题 (\d+) · (\d+\.\d+)[::](.+)$', txt, re.M):
out.append({
'no': int(m.group(1)),
'kp': m.group(2),
'core': m.group(3).strip(),
'heading': m.group(0).strip().lstrip('#').strip(),
})
return out
def scan_kp_names(inv_path):
"""盘点里的 (X.Y -> 章节名)"""
names = {}
for m in re.finditer(r'^#{3,4} (\d+\.\d+) (.+)$', read(inv_path), re.M):
if m.group(1).startswith('0.'):
continue
names[m.group(1)] = m.group(2).strip()
return names
def scan_quick(kp_path):
"""速查卡 (X.Y -> (章节标题, 锚点))"""
m = {}
txt = read(kp_path)
# 记录每个 ## 标题与它下方最近的 <!-- KP: ... -->
blocks = re.split(r'^(## .+)$', txt, flags=re.M)
cur = None
for seg in blocks:
if seg.startswith('## '):
cur = seg[3:].strip()
continue
if cur:
hit = re.search(r'<!--\s*KP:\s*([0-9.,\s]+?)\s*-->', seg)
if hit:
for kp in hit.group(1).split(','):
kp = kp.strip()
if kp:
m[kp] = (cur, anchor(cur))
return m
def build(d, check_only=False):
# 点文件:`NN-点K-*.md`(兼容 02..09 老讲次与 10 以上的新讲次)
# 也兼容 `08b-点7-*.md` 这类"同一知识点拆多册"的命名(超 1.3 万字符时的拆法)
point_files = sorted(fn for fn in os.listdir(d)
if re.match(r'^\d{2}[a-z]?-点', fn) and fn.endswith('.md'))
inv = os.path.join(d, '01-知识点盘点.md')
if not os.path.exists(inv):
cand = [fn for fn in sorted(os.listdir(d))
if re.match(r'^01-.*盘点.*\.md$', fn)]
if cand:
inv = os.path.join(d, cand[0])
quick = None
for fn in sorted(os.listdir(d)):
if '速查卡' in fn and fn.endswith('.md'):
quick = os.path.join(d, fn)
break
kp_names = scan_kp_names(inv)
QFN = os.path.basename(quick) if quick else '10-速查卡.md'
kp_quick = scan_quick(quick) if quick and os.path.exists(quick) else {}
# 全量题目索引
index = {} # (file, no) -> item
by_kp = {} # kp -> [item] 按 (文件名, 题号) 排序
for order, fn in enumerate(point_files):
m = re.match(r'^\d{2}[a-z]?-点(\d+)', fn)
pno = int(m.group(1)) if m else order + 1
for it in scan_point_file(os.path.join(d, fn)):
it['file'] = fn
it['order'] = order
it['point'] = pno
it['anchor'] = anchor(it['heading'])
index[(fn, it['no'])] = it
by_kp.setdefault(it['kp'], []).append(it)
for kp in by_kp:
by_kp[kp].sort(key=lambda x: (x['order'], x['no']))
# ---- 1. 注入关联行 ----
changed = 0
for fn in point_files:
path = os.path.join(d, fn)
txt = read(path)
lines = txt.split('\n')
out = []
i = 0
# 逐题处理:找到题标题,收集到下一个 '---' 分隔线或下一个题标题为止
marks = []
for k, ln in enumerate(lines):
m = re.match(r'^### 题 (\d+) · ', ln)
if m:
marks.append((k, int(m.group(1))))
if not marks:
continue
bounds = []
for j, (k, no) in enumerate(marks):
end = marks[j + 1][0] if j + 1 < len(marks) else len(lines)
bounds.append((k, no, end))
pos = 0
new = []
for k, no, end in bounds:
new.extend(lines[pos:k])
body = lines[k:end]
# 去掉已有 关联 行与其后空行
body = [b for b in body if not b.startswith('> **关联**')]
while body and body[-1].strip() == '':
body.pop()
# 修剪尾部孤立的 '---'
while body and body[-1].strip() == '---':
body.pop()
it = index[(fn, no)]
kp = it['kp']
peers = by_kp[kp]
me = peers.index(it)
ups = peers[:me][-2:]
downs = peers[me + 1:][:2]
inv_name = kp_names.get(kp, '')
inv_link = '[§%s %s](01-知识点盘点.md#user-content-%s)' % (
kp, inv_name, anchor('%s %s' % (kp, inv_name))) if inv_name else '§' + kp
def fmt(items):
if not items:
return '—'
return '、'.join('[点 %d 题 %d](%s#user-content-%s)' % (
it2['point'], it2['no'], it2['file'], it2['anchor'])
for it2 in items)
if kp in kp_quick:
qtitle, qanc = kp_quick[kp]
qlink = '[%s](%s#user-content-%s)' % (qtitle, QFN, qanc)
else:
qlink = '—'
body.append('')
body.append('> **关联** · 盘点 %s | 上游 %s | 下游 %s | 速查 %s'
% (inv_link, fmt(ups), fmt(downs), qlink))
body.append('')
body.append('---')
body.append('')
new.extend(body)
pos = end
new.extend(lines[pos:])
res = '\n'.join(new)
res = re.sub(r'\n{3,}', '\n\n', res)
if res != txt:
changed += 1
if not check_only:
write(path, res)
# ---- 2. 生成 §0.4 ----
# 反查表写到"含 AUTO:KP 标记的那份文件"——默认是盘点,但盘点超过 1.3 万字符时
# 可以把表迁到 01b(标记跟着走),脚本不必改。找不到标记就退回盘点。
target = inv
if not (os.path.exists(inv) and '<!-- AUTO:KP -->' in read(inv)):
for fn in sorted(os.listdir(d)):
p = os.path.join(d, fn)
if fn.endswith('.md') and os.path.exists(p) and '<!-- AUTO:KP -->' in read(p):
target = p
break
if os.path.exists(target):
txt = read(target)
rows = ['| 盘点章节(知识点) | 对应题目 |', '|---|---|']
all_kps = sorted(kp_names, key=lambda s: tuple(int(x) for x in s.split('.')))
for kp in all_kps:
items = by_kp.get(kp, [])
if items:
cell = '、'.join('[点 %d 题 %d](%s#user-content-%s)' % (
it['point'], it['no'], it['file'], it['anchor']) for it in items)
else:
cell = '(本讲未单独配题)'
rows.append('| §%s %s | %s |' % (kp, kp_names[kp], cell))
table = '\n'.join(rows)
new_txt = re.sub(r'<!-- AUTO:KP -->.*?<!-- /AUTO:KP -->',
'<!-- AUTO:KP -->\n' + table + '\n<!-- /AUTO:KP -->',
txt, flags=re.S)
if new_txt != txt:
changed += 1
if not check_only:
write(target, new_txt)
# ---- 3. 生成速查卡「回查」表 ----
if quick and os.path.exists(quick):
txt = read(quick)
if '<!-- AUTO:回查 -->' in txt:
blocks = re.split(r'^(## .+)$', txt, flags=re.M)
rows = ['| 想查什么 | 对应题目 |', '|---|---|']
cur = None
for seg in blocks:
if seg.startswith('## '):
cur = seg[3:].strip()
continue
if not cur or cur == '回查':
continue
hit = re.search(r'<!--\s*KP:\s*([0-9.,\s]+?)\s*-->', seg)
if not hit:
continue
items = []
for kp in hit.group(1).split(','):
kp = kp.strip()
items.extend(by_kp.get(kp, []))
items.sort(key=lambda x: (x['order'], x['no']))
if items:
cell = '、'.join('[点 %d 题 %d](%s#user-content-%s)' % (
it['point'], it['no'], it['file'], it['anchor'])
for it in items)
rows.append('| %s | %s |' % (cur, cell))
tbl = '\n'.join(rows)
new_txt = re.sub(r'<!-- AUTO:回查 -->.*?<!-- /AUTO:回查 -->',
'<!-- AUTO:回查 -->\n' + tbl + '\n<!-- /AUTO:回查 -->',
txt, flags=re.S)
if new_txt != txt:
changed += 1
if not check_only:
write(quick, new_txt)
total = len(index)
print('%s: %d 个点文件, %d 题, %d 个知识点, %d 个文件更新'
% (os.path.basename(d.rstrip('/\\')), len(point_files), total,
len(kp_names), changed))
miss = [kp for kp in kp_names if kp not in by_kp]
if miss:
print(' 未配题的知识点: ' + ', '.join('§' + k for k in miss))
bad = [it for it in index.values() if it['kp'] not in kp_names]
if bad:
print(' !! 题目指向不存在的盘点章节: ' +
', '.join('%s 题%d(§%s)' % (it['file'], it['no'], it['kp']) for it in bad))
if __name__ == '__main__':
args = [a for a in sys.argv[1:] if not a.startswith('--')]
check = '--check' in sys.argv
for d in args:
build(d, check)