Files
yanxuan/脚本/audit_all_tables.py
T
Your Name 7d596c867e 沉淀2027推免名单离线解析与原件删除边界
磁盘告急且采集额度中断,改为只吃已落盘原件:15份官方推免公示PDF与
合肥工业1679行名单解析成 y2027_tuimian_2027(11校1436行),华南理工
统考可用计划单独入 y2027_plan_2027,避免与推免接收人数混口径。

判据修正三处会造出假数的地方:汇总/合计行先排除再分组、研究生支教团等
专项计划行不计入接收人数、PDF抽出的Kangxi兼容部首折回正规汉字(否则
跨源关联键静默漏配)。东南大学同批既有官方计数表又有逐人名单,名单分组
多278人判为口径差异,只入官方计数、182行推导值留作对账不入库。

校验器先被故意改坏验证过一轮才用于正式入库;备份脚本取错 description
下标导致备份写成空值,已重做并回读核验。
2026-11-01 00:25:29 +08:00

206 lines
9.7 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.
"""全表审计引擎:187 张非空表逐张全量检查(不抽样)。
每张表检查 7 类问题:
P1 业务键重复 (school_id, major_id, year) / (st_number) / ID 列
P2 孤儿记录 school_id / major_id 找不到维度行
P3 年份越界 year 不在 [2020, 2028]
P4 高缺失字段 空值率 > 50%
P5 数值异常 负数 / 超范围(分数>500 等)
P6 格式异常 院校码非 5 位、专业码非 4-6 位、年份非 4 位
P7 结构异常 单行表 / 全字段同值(疑似占位表)
输出:
审计报告/全表审计_汇总.csv
审计报告/全表审计_字段剖面.csv
审计报告/全表审计_问题清单.csv
审计报告/全表审计_报告.md
"""
import csv
import os
import re
import sqlite3
import time
DB = r'D:\择校\数据库\zexiao_2027.db'
OUT = r'D:\择校\审计报告'
con = sqlite3.connect(DB, timeout=1800)
con.execute('PRAGMA temp_store=MEMORY')
con.execute('PRAGMA cache_size=-262144')
# ---------- 维度基准 ----------
SCH = {str(int(r[0])) for r in con.execute('SELECT school_id FROM ggyx_dim_school')}
MAJ = {str(int(r[0])) for r in con.execute('SELECT major_id FROM ggyx_dim_major')}
# 已登记语义的字段:不按格式/越界/孤儿报错(人工肉眼审查后定案为正常语义)
try:
SEM = {(r[0], r[1]) for r in con.execute('SELECT table_name, field_name FROM dim_field_semantics')}
SEM_WILD = {r[0] for r in con.execute("SELECT table_name FROM dim_field_semantics WHERE field_name='*'")}
except Exception:
SEM, SEM_WILD = set(), set()
print('维度基准:院校 %d / 专业 %d' % (len(SCH), len(MAJ)))
tabs = [r[0] for r in con.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")]
summary, profile, issues = [], [], []
t_all = time.time()
for idx, t in enumerate(tabs, 1):
try:
cols = [(r[1], r[2]) for r in con.execute('PRAGMA table_info("%s")' % t)]
n = con.execute('SELECT COUNT(*) FROM "%s"' % t).fetchone()[0]
except Exception as e:
print(' 跳过 %s: %s' % (t, str(e)[:40]))
continue
if not n:
continue
cn = [c for c, _ in cols]
t0 = time.time()
n_issue = [0]
def add(level, kind, field, detail, count, _t=t, _n=n, _acc=n_issue):
if count:
issues.append([_t, level, kind, field, count, round(100.0 * count / _n, 3), detail])
_acc[0] += 1
# ---- P7 单行表 ----
if n == 1 and t not in SEM_WILD:
add('P7', '单行表', '', '整表仅 1 行,疑似占位', 1)
# ---- P1 业务键重复(仅维度/映射表;事实表一行本就是明细,重复属正常)----
DIM_LIKE = ('dim_', 'school_major', 'school_adjust_major', 'major_map', 'ssd_master', 'src_major_catalog')
if any(k in t for k in DIM_LIKE) and 'school_id' in cn and 'major_id' in cn \
and (t, 'school_id,major_id') not in SEM:
key = 'school_id,major_id'
try:
d = con.execute('SELECT COUNT(*) FROM (SELECT 1 FROM "%s" GROUP BY %s HAVING COUNT(*)>1)' % (t, key)).fetchone()[0]
add('P1', '业务键重复', key, '(%s) 重复出现多行' % key, d)
except Exception:
pass
for idcol in ('notice_id', 'record_pk', 'news_id', 'article_id'):
if (t, idcol) in SEM:
continue
if idcol in cn:
try:
d = con.execute('''SELECT COUNT(*) FROM (SELECT "%s" FROM "%s"
WHERE IFNULL("%s",'')<>'' GROUP BY 1 HAVING COUNT(*)>1)''' % (idcol, t, idcol)).fetchone()[0]
add('P1', 'ID 重复', idcol, '%s 有重复值' % idcol, d)
except Exception:
pass
break
# ---- P2 孤儿 ----
if 'school_id' in cn:
try:
# 有 school_id_ggyx 映射列(第三方源自有 ID 体系)的表,校验映射列
idcol = 'school_id'
if any(r[0] == 'school_id_ggyx' for r in cols):
idcol = 'school_id_ggyx'
sids = {str(int(x[0])) for x in con.execute('SELECT DISTINCT CAST(%s AS INTEGER) FROM "%s" WHERE %s IS NOT NULL' % (idcol, t, idcol))}
d = len(sids - SCH)
add('P2', '孤儿 school_id', idcol, '%d 个 %s 不在 dim_school(如 %s)'
% (d, idcol, ','.join(sorted(sids - SCH)[:5])), d)
except Exception:
pass
if 'major_id' in cn and t != 'ggyx_dim_major' and (t, 'major_id') not in SEM:
try:
mids = {str(int(x[0])) for x in con.execute('SELECT DISTINCT CAST(major_id AS INTEGER) FROM "%s" WHERE major_id IS NOT NULL' % t)}
d = len(mids - MAJ)
add('P2', '孤儿 major_id', 'major_id', '%d 个 major_id 不在 dim_major(如 %s)'
% (d, ','.join(sorted(mids - MAJ)[:5])), d)
except Exception:
pass
# ---- P3 年份越界 ----
if 'year' in cn and (t, 'year') not in SEM:
try:
d = con.execute('SELECT COUNT(*) FROM "%s" WHERE year IS NOT NULL AND (year<2018 OR year>2028)' % t).fetchone()[0]
add('P3', '年份越界', 'year', 'year 不在 [2018,2028]', d)
except Exception:
pass
# ---- 字段剖面 + P4/P5/P6 ----
for c, typ in cols:
try:
if c.lower() in ('file_sha256', 'row_sha256', 'raw_json', 'raw_rel', '_ingested_at',
'recorded_at', 'ingested_at', '_at', 'source_file_sha256', 'key_json',
'path', 'introduce', 'avatar'):
nn = con.execute('SELECT COUNT("%s") FROM "%s"' % (c, t)).fetchone()[0]
nd = ''
else:
nn, nd = con.execute('SELECT COUNT("%s"), COUNT(DISTINCT "%s") FROM "%s"' % (c, c, t)).fetchone()
except Exception:
continue
miss = round(100.0 * (n - nn) / n, 2)
mn = mx = ''
is_num = any(k in (typ or '').upper() for k in ('INT', 'REAL', 'NUM', 'DEC'))
if is_num and nn:
try:
mn, mx = con.execute('SELECT MIN("%s"), MAX("%s") FROM "%s"' % (c, c, t)).fetchone()
except Exception:
pass
profile.append([t, c, typ or '', n, nn, miss, nd, mn, mx])
if miss > 50 and nn > 0 and t not in SEM_WILD and (t, c) not in SEM:
add('P4', '高缺失字段', c, '空值率 %.1f%%' % miss, n - nn)
if is_num and nn:
FLAGGED = "IFNULL(data_flag,'')<>''" if 'data_flag' in cn else '0'
if c in ('score', 'cs_all_result', 'fs_result', 'all_result'):
try:
d = con.execute('SELECT COUNT(*) FROM "%s" WHERE (CAST("%s" AS REAL)<0 OR CAST("%s" AS REAL)>500) AND NOT %s' % (t, c, c, FLAGGED)).fetchone()[0]
add('P5', '分数越界', c, '分数 <0 或 >500(未标记)', d)
except Exception:
pass
if c in ('fs_total', 'nlq_total', 'taotai_total', 'num', 'plan', 'admitted', 'applicants'):
try:
d = con.execute('SELECT COUNT(*) FROM "%s" WHERE CAST("%s" AS REAL)<0 AND NOT %s' % (t, c, FLAGGED)).fetchone()[0]
add('P5', '负数', c, '人数类字段出现负值(未标记)', d)
except Exception:
pass
if c in ('dwdm', 'school_code', '院校代码') and (t, c) not in SEM:
try:
d = con.execute('SELECT COUNT(*) FROM "%s" WHERE IFNULL("%s",\'\')<>\'\' AND LENGTH("%s")<>5' % (t, c, c)).fetchone()[0]
add('P6', '院校码非5位', c, '院校代码应 5 位', d)
except Exception:
pass
if c in ('zydm', 'code', '专业代码', 'maj_code', 'c_code') and (t, c) not in SEM:
try:
d = con.execute('''SELECT COUNT(*) FROM "%s" WHERE IFNULL("%s",'')<>''
AND LENGTH("%s") NOT BETWEEN 4 AND 6''' % (t, c, c)).fetchone()[0]
add('P6', '专业码长度异常', c, '专业码应 4-6 位(含字母码)', d)
except Exception:
pass
lvl = '严重' if any(i[1] in ('P1', 'P2') for i in issues if i[0] == t) else (
'中' if any(i[1] in ('P3', 'P5', 'P6') for i in issues if i[0] == t) else
('低' if n_issue[0] else '无'))
summary.append([t, n, len(cols), n_issue[0], lvl, round(time.time() - t0, 1)])
if idx % 20 == 0 or n >= 500000:
print(' [%3d/%d] %-32s %9s 行 %2d 问题 %.1fs'
% (idx, len(tabs), t, f'{n:,}', n_issue[0], time.time() - t0))
os.makedirs(OUT, exist_ok=True)
with open(os.path.join(OUT, '全表审计_汇总.csv'), 'w', encoding='utf-8-sig', newline='') as f:
w = csv.writer(f)
w.writerow(['表', '行数', '列数', '问题数', '严重度', '耗时秒'])
w.writerows(sorted(summary, key=lambda x: -x[1]))
with open(os.path.join(OUT, '全表审计_字段剖面.csv'), 'w', encoding='utf-8-sig', newline='') as f:
w = csv.writer(f)
w.writerow(['表', '字段', '类型', '总行数', '非空数', '空值率%', '唯一值数', '最小值', '最大值'])
w.writerows(profile)
with open(os.path.join(OUT, '全表审计_问题清单.csv'), 'w', encoding='utf-8-sig', newline='') as f:
w = csv.writer(f)
w.writerow(['表', '级别', '问题类型', '字段', '异常数', '占比%', '说明'])
w.writerows(issues)
print()
print('=== 完成,总耗时 %.1f 分 ===' % ((time.time() - t_all) / 60))
print('表 %d / 字段剖面 %d / 问题 %d' % (len(summary), len(profile), len(issues)))
print()
print('按级别:')
for k in ('P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7'):
cnt = [i for i in issues if i[1] == k]
if cnt:
print(' %s %-16s %3d 项,涉及 %d 张表' % (k, cnt[0][2], len(cnt), len({i[0] for i in cnt})))
con.close()