Files
MathNotesVersion2/.workbuddy/tools/md2pdf/gen_crosslinks.py
T
Yimu 41b36b2b3c 线代第4-6讲补全:线性方程组43题、特征值35题、二次型30题(知识点带题+题级链接)
- 第4讲 线性方程组:8 个点分册 43 题,旧版题点分离整目录归档到 旧版-题点分离/
- 第5讲 特征值与特征向量:7 个点分册 35 题
- 第6讲 二次型:7 个点分册 30 题(含合同与相似、二次曲面两节)
- 每讲 01-知识点盘点 + 10 个文件 + 速查卡回查表,全部题目级双向链接
- gen_crosslinks.py 新增:由题目标题单一数据源生成关联行/盘点§0.4/速查回查表
- fix_gitea_math.py 支持 --scope 指向目录(新建未跟踪文件也能修)
- 校验:184-248 条内部链接 0 异常,公式 0 处待修,单文件均 <1.3 万字符
2026-10-24 16:38:01 +08:00

261 lines
9.4 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):
point_files = sorted(fn for fn in os.listdir(d)
if re.match(r'^0[2-9]-', fn) and fn.endswith('.md'))
inv = os.path.join(d, '01-知识点盘点.md')
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):
for it in scan_point_file(os.path.join(d, fn)):
it['file'] = fn
it['order'] = order
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['order'] + 1, 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 ----
if os.path.exists(inv):
txt = read(inv)
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['order'] + 1, 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(inv, 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['order'] + 1, 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)