#!/usr/bin/env node /* ========================================================================== Linux 专题 · 指标体检(SPEC v1 §12) 用法:node tools/check-metrics.js # 全部章节 node tools/check-metrics.js 06-proc.html # 指定章节 node tools/check-metrics.js --quiet # 只输出结论 与 check-pages.js 的分工: check-pages.js 结构(标题/侧栏/锚点/标签配对/代码块转义)——它不认识本文件的指标 check-metrics.js 内容形态(密度/段长/句长/并列项/take/章骨架/图/易错点/mark) 口径(与 SPEC §3 一致,改口径要同时改 SPEC): 正文 =
内剔除
、.tablewrap、
三个块之后的全部文本 密度 = 正文内的 个数 ÷ 正文汉字数 × 100 ========================================================================== */ const fs = require("fs"); const path = require("path"); const root = path.resolve(__dirname, ".."); const cfg = JSON.parse(fs.readFileSync(path.join(__dirname, "metrics.config.json"), "utf8")); const R = cfg.rules; const args = process.argv.slice(2).filter(a => !a.startsWith("--")); const quiet = process.argv.includes("--quiet"); const files = args.length ? args : fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort(); const cjk = s => (s.replace(/[\u4e00-\u9fff]/g, "x").match(/x/g) || []).length; const text = h => h.replace(/<[^>]+>/g, "").replace(/&[a-z#0-9]+;/gi, " ").replace(/\s+/g, " ").trim(); const count = (s, re) => (s.match(re) || []).length; const num = (f, v) => `${f.padEnd(22)}${String(v).padStart(6)}`; /* 去掉不该计入正文的三个块 */ function cleanArticle(art) { return art .replace(//gi, " ") .replace(//gi, " ") .replace(//gi, " "); } const paraRe = /]*)>([\s\S]*?)<\/p>/gi; const sentences = t => t.split(/[。!?!?]+/).map(s => s.trim()).filter(Boolean); /* SPEC §7.3:take 的两种形态——复述句带因果词,判据句带动作词 */ const CAUSAL = /因为|所以|只能|才会|才|即|由于|导致|根本原因/; const ACTION = /先|要|别|不要|交给|必须先|应|勿|防止|建议/; /* 章骨架检查:preamble = 第一个 h3 之前 */ function skeleton(html, art, numStr) { const h3s = [...art.matchAll(/]*id="(sec-[\d-]+)"[^>]*>([\s\S]*?)<\/h3>/gi)]; const firstH3 = h3s.length ? art.indexOf(h3s[0][0]) : art.length; const pre = art.slice(0, firstH3); const out = {}; const okBox = [...pre.matchAll(/
([\s\S]*?)<\/div>/gi)] .some(m => /直答|30\s*秒/.test(text(m[1]))); out.answer = okBox; const howTo = [...pre.matchAll(/
([\s\S]*?)<\/div>/gi)] .some(m => /怎么读/.test(text(m[1]))); out.howto = howTo; let terms = false, termRows = 0; const h4s = [...pre.matchAll(/]*>([\s\S]*?)<\/h4>/gi)]; for (const m of h4s) { if (!/个词|术语|速查/.test(text(m[1]))) continue; const tail = pre.slice(m.index); const tbl = tail.match(/
([\s\S]*?)<\/div>/i); if (!tbl) continue; termRows = count(tbl[1], //g) - 1; if (termRows >= 5 && termRows <= 7) terms = true; } out.terms = terms; out.termRows = termRows; const sum = art.match(new RegExp(`

`, "i")); out.sum = !!sum; out.symptom = false; out.symptomRows = 0; if (sum) { const tail = art.slice(sum.index); const tbl = tail.match(/
([\s\S]*?)<\/div>/i); if (tbl) { const th = count(tbl[1], //g); out.symptomRows = count(tbl[1], //g) - 1; out.symptom = th === 3 && out.symptomRows > 0 && out.symptomRows <= R.symptomRows; } } return { out, h3s }; } const rows = []; const problems = []; const err = (f, m) => problems.push({ f, m, level: "error" }); const warn = (f, m) => problems.push({ f, m, level: "warn" }); let densitySum = 0, densityFiles = 0; for (const f of files) { const html = fs.readFileSync(path.join(root, f), "utf8"); const art = (html.match(/
([\s\S]*?)<\/article>/) || [, ""])[1]; if (!art) { err(f, "缺少
,跳过"); continue; } const numStr = String(parseInt(f.slice(0, 2), 10)); const type = cfg.chapters[f.slice(0, 2)] || "B"; const T = cfg.types[type]; const clean = cleanArticle(art); /* ---- 密度 ---- */ const chars = cjk(clean); const codes = count(clean, / T.density) err(f, `密度 ${density} 超过 ${type} 类上限 ${T.density}(正文 ${chars} 字 / ${codes} 个 code)`); } /* ---- 段落、句长、并列项、code 集中度 ---- */ let paras = 0, paraChars = 0, longParas = 0, denseParas = 0, listyParas = 0; let sentTotal = 0, sentOver = 0, sentOverHard = 0, maxSent = 0; const worstSent = []; for (const m of clean.matchAll(paraRe)) { if (/class="chapnav"/.test(m[1])) continue; const t = text(m[2]); if (!t) continue; paras++; const n = cjk(t); paraChars += n; if (n > R.paragraphHardMax) err(f, `段落 ${n} 字超过硬红线 ${R.paragraphHardMax}:「${t.slice(0, 24)}…」`); else if (n > R.paragraphMax) longParas++; const c = count(m[2], / R.codePerParagraph) { denseParas++; if (c >= 6 && T.density !== null) err(f, `段落含 ${c} 个 (上限 ${R.codePerParagraph}):「${t.slice(0, 24)}…」`); } const circled = count(t, /[①②③④⑤⑥⑦⑧⑨⑩]/g); if (circled >= 4 || (circled >= 3 && n > 120)) listyParas++; for (const s of sentences(t)) { const sn = cjk(s); sentTotal++; if (sn > maxSent) maxSent = sn; if (sn > R.sentenceOver) { sentOverHard++; if (worstSent.length < 40) worstSent.push(sn); } if (sn > R.sentenceMax) sentOver++; } } const paraAvg = paras ? +(paraChars / paras).toFixed(1) : 0; if (T.density !== null && paraAvg > R.paragraphAvg) warn(f, `段均 ${paraAvg} 字 > ${R.paragraphAvg}`); if (sentOverHard > R.sentenceOverPerChapter) err(f, `超长句(>${R.sentenceOver} 汉字)${sentOverHard} 句 > ${R.sentenceOverPerChapter}(最长 ${maxSent} 字)`); if (listyParas) warn(f, `${listyParas} 个段落并列项 ≥4(①②③ 塞进一句话,应改列表)`); if (T.maxLooseParagraphs && paras > T.maxLooseParagraphs) err(f, `散段落 ${paras} > ${T.maxLooseParagraphs}(速查/题库章应以表格承载)`); /* ---- 小节、take、标识符重复 ---- */ const { out: sk, h3s } = skeleton(html, art, numStr); const sections = h3s.length; if (sections < T.sections[0] || sections > T.sections[1]) warn(f, `小节 ${sections} 个,SPEC 要求 ${T.sections[0]}–${T.sections[1]}`); let takeOk = 0; const missingTake = []; const identCount = new Map(); const secTexts = []; h3s.forEach((m, i) => { const start = m.index + m[0].length; const end = i + 1 < h3s.length ? h3s[i + 1].index : art.length; const body = art.slice(start, end); const secText = cleanArticle(body).split(/([\s\S]*?)<\/p>/i); if (!tk) missingTake.push(m[2].replace(/<[^>]+>/g, "").slice(0, 18)); else { const t = text(tk[1]).replace(/^一句话[::]\s*/, ""); let bad = false; if (cjk(t) > R.takeMax) { err(f, `take 超长(${cjk(t)} 字 > ${R.takeMax})`); bad = true; } else if (/^(本节|这一节)/.test(t)) { err(f, `take 是摘要句(以「${t.slice(0, 6)}」开头),应写成判据句`); bad = true; } /* SPEC §7.3 硬校验:不得照搬本节标题(连续 6 个汉字重合) */ const norm = s => s.replace(/[\s,、::;;()()「」《》·—–\-]/g, ""); const title = norm(text(m[2]).replace(/^\s*\d+\.\d+\s*/, "")); const tk2 = norm(t); for (let p = 0; p + 6 <= title.length && !bad; p++) { const win = title.slice(p, p + 6); /* 只比中文窗口:文件名、命令名撞车不算"照搬标题" */ if (win.length === 6 && cjk(win) >= 4 && tk2.includes(win)) { err(f, `take 照搬了本节标题「${win}…」,应改成一句话结论`); bad = true; } } /* 提示:纯定义句是合法的结论复述,机器判不准,只提醒 */ if (!bad && !CAUSAL.test(t) && !ACTION.test(t)) { warn(f, `take 未出现因果词或动作词,偏百科腔,建议补一句判据:「${t.slice(0, 20)}…」`); } if (!bad) takeOk++; } for (const c of secText.matchAll(/]*>([\s\S]*?)<\/code>/gi)) { const k = text(c[1]); if (!k || k.length > 40) continue; identCount.set(k, (identCount.get(k) || 0) + 1); } }); const repeatIds = [...identCount.entries()].filter(([, v]) => v > R.codePerIdentifier).sort((a, b) => b[1] - a[1]); if (missingTake.length) err(f, `${missingTake.length}/${sections} 节缺 take:${missingTake.slice(0, 4).join(" / ")}${missingTake.length > 4 ? " …" : ""}`); if (repeatIds.length) warn(f, `${repeatIds.length} 个标识符被重复包 code >${R.codePerIdentifier} 次(最多:${repeatIds.slice(0, 3).map(([k, v]) => `${k}×${v}`).join("、")})`); /* ---- 骨架 ---- */ const needAnswer = type === "C" ? false : true; if (needAnswer && !sk.answer) err(f, "章首缺「30 秒直答」框(box ok + 直答)"); if (needAnswer && !sk.howto) err(f, "章首缺「怎么读这一章」(box tip)"); if (needAnswer && !sk.terms) err(f, `章首缺术语速查表(5–7 行,当前 ${sk.termRows} 行)`); if (!sk.sum) err(f, `缺章末回顾

`); if (sk.sum && !sk.symptom) err(f, `缺「症状 → 先查什么 → 回哪节」表(三列、≤${R.symptomRows} 行,当前 ${sk.symptomRows} 行)`); /* ---- 图、易错点、可跳过、mark ---- */ const figures = count(art, /]*class="figure"/gi); if (figures < T.figures) err(f, `图 ${figures} 张 < 目标 ${T.figures}(${type} 类)`); const warns = [...art.matchAll(/
([\s\S]*?)<\/div>/gi)].map(m => text(m[1])); const mistakes = warns.filter(t => /易错点/.test(t)); const badMistake = mistakes.filter(t => !(/现象/.test(t) && /原因/.test(t) && /(怎么验证|验证)/.test(t))); if (mistakes.length < R.mistakes[0] || mistakes.length > R.mistakes[1]) warn(f, `易错点 ${mistakes.length} 处,SPEC 要求 ${R.mistakes[0]}–${R.mistakes[1]}`); if (badMistake.length) err(f, `${badMistake.length} 处易错点缺「现象/原因/怎么验证」三要素`); const skippable = count(art, /class="tag s"/g) + warns.filter(t => /可跳过/.test(t)).length; if (skippable < R.skippable[0] || skippable > R.skippable[1]) warn(f, `可跳过 ${skippable} 处,SPEC 要求 ${R.skippable[0]}–${R.skippable[1]}`); const marks = count(art, / R.mark) err(f, ` ${marks} 处(SPEC 禁用,强调交给 take 与 box)`); /* ---- 篇幅 ---- */ if (chars < T.chars[0] || chars > T.chars[1]) warn(f, `正文 ${chars} 字,SPEC 建议 ${T.chars[0]}–${T.chars[1]}`); rows.push({ f, type, density: T.density === null ? "—" : density, cap: T.density ?? "—", paraAvg, longParas, denseParas, sentOverHard, listyParas, take: `${takeOk}/${sections}`, figures, mistakes: mistakes.length, skippable, marks, chars, skeleton: [sk.answer, sk.terms, sk.howto, sk.sum, sk.symptom].map(v => (v ? "●" : "○")).join("") }); } /* ---------------- 输出 ---------------- */ const pad = (s, n) => String(s).padEnd(n); if (!quiet) { console.log("§ 指标体检(口径:article 内剔除 pre/tablewrap/figure 的全文)\n"); console.log(pad("文件", 20) + pad("型", 4) + pad("密度/上限", 12) + pad("段均", 7) + pad("超200", 7) + pad("code≥5", 8) + pad("句>80", 7) + pad("并列≥4", 8) + pad("take", 8) + pad("图", 5) + pad("易错", 6) + pad("可跳", 6) + pad("mark", 6) + "骨架"); for (const r of rows) { console.log(pad(r.f, 20) + pad(r.type, 4) + pad(`${r.density}/${r.cap}`, 12) + pad(r.paraAvg, 7) + pad(r.longParas, 7) + pad(r.denseParas, 8) + pad(r.sentOverHard, 7) + pad(r.listyParas, 8) + pad(r.take, 8) + pad(r.figures, 5) + pad(r.mistakes, 6) + pad(r.skippable, 6) + pad(r.marks, 6) + r.skeleton); } console.log("\n骨架顺序:直答 术语 怎么读 回顾 症状表(● 有 / ○ 无)"); const avg = densityFiles ? +(densitySum / densityFiles).toFixed(2) : 0; console.log(`全库平均密度 ${avg}(目标 ≤${R.avgDensity});正文合计 ${rows.reduce((a, r) => a + r.chars, 0)} 字`); } const errs = problems.filter(p => p.level === "error"); const warns = problems.filter(p => p.level === "warn"); if (!quiet) { if (problems.length) { console.log(""); let cur = ""; for (const p of problems) { if (p.f !== cur) { cur = p.f; console.log(`\n${cur}`); } console.log(` ${p.level === "error" ? "✗" : "!"} ${p.m}`); } } } console.log(`\n结论:${files.length} 章 · 硬问题 ${errs.length} 项 · 提示 ${warns.length} 项 · ` + `${errs.length ? "未达标" : "全部达标"}`); if (errs.length) process.exit(1);