- 01-知识点盘点 14038 → 12976 字符,超额部分整体迁到 01b(§0.x 编号保持不变) - 15-点14-概率多维随机变量 补题并同步速查回查 - gen_crosslinks 支持把索引表写入含 AUTO:KP 标记的 01b
276 lines
10 KiB
Python
276 lines
10 KiB
Python
# -*- 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 以上的新讲次)
|
||
point_files = sorted(fn for fn in os.listdir(d)
|
||
if re.match(r'^\d{2}-点', 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):
|
||
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 ----
|
||
# 反查表写到"含 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['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(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['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)
|