Files
PoliticsNotes/题库/generate_zhenti_sections.py

144 lines
5.7 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 -*-
"""把 SQLite 题库中的真题按考点生成「真题精练」区,插入马原各专题文件。
映射:真题营考点名 → 马原专题号(对齐 马克思主义基本原理.md 的 9 个专题)。
插入位置:每专题文件 "## 三、易混点速查" 之前。
用法:python generate_zhenti_sections.py
"""
import os, re, sqlite3, json, ast
HERE = os.path.dirname(os.path.abspath(__file__))
DB = os.path.join(HERE, "zhenti_kaodian.db")
NOTE_DIR = r"D:\考研\考研政治\政治笔记\马原"
# 真题营考点名 → 马原专题号
TOPIC_MAP = {
"马克思主义的创立与发展": 1,
"主观能动性与客观规律性": 2, "物质与意识的辩证关系": 2, "世界的物质统一性": 2, "运动与静止": 2,
"联系与发展": 3, "必然性与偶然性": 3, "对立统一规律": 3, "量变质变规律": 3,
"矛盾的普遍性与特殊性": 3, "否定之否定规律": 3,
"实践是认识的基础": 4, "真理与价值": 4, "感性认识与理性认识": 4,
"认识的反复性与无限性": 4, "认识的两次飞跃": 4,
"社会存在与社会意识": 5, "经济基础与上层建筑": 5, "生产力与生产关系": 5,
"人民群众是历史的创造者": 5, "个人在历史上的作用": 5, "社会形态更替": 5, "社会基本矛盾": 5,
"商品二因素与劳动二重性": 6,
"剩余价值的生产": 7, "资本的有机构成": 7, "资本主义经济危机": 7,
"垄断资本主义与金融资本": 8,
"共产主义社会的基本特征": 9, "无产阶级革命与马克思主义政党": 9, "两个必然与两个决不会": 9,
}
SUBJ_PAT = "马原"
def load_questions():
con = sqlite3.connect(DB)
con.row_factory = sqlite3.Row
cur = con.cursor()
rows = cur.execute(
"SELECT k.name AS kp, k.subject, z.* FROM zhenti z JOIN kaodian k ON k.id=z.kaodian_id"
).fetchall()
con.close()
qs = []
for r in rows:
if SUBJ_PAT not in r["subject"]:
continue
opts = ast.literal_eval(r["options"]) if r["options"] else []
qs.append({
"kp": r["kp"], "year": r["year"], "qno": r["qno"], "type": r["qtype"],
"stem": r["stem"], "opts": opts, "answer": r["answer"],
"analysis": r["analysis"] or "", "note": r["note"] or "", "url": r["url"],
})
# 去重:同一 年份+题号+考点 只留一条(跨科目重复考点会重复出现)
seen, uniq = set(), []
for q in sorted(qs, key=lambda x: (x["year"], x["qno"])):
key = (q["year"], q["qno"], q["kp"])
if key in seen:
continue
seen.add(key)
uniq.append(q)
return uniq
def fmt_options(opts):
return " ".join(f"{o['letter']}. {o['text']}" for o in opts)
def fmt_analysis(a, limit=240):
a = re.sub(r"\n+", " ", a).strip()
if len(a) > limit:
return a[:limit] + "……"
return a
def build_section(qs):
if not qs:
return ""
lines = [
"### 真题精练(真题营 2010—2026 全量真题)",
"",
"> 来源:真题营 https://zhenti.zalize.com/zhenti/kaodian(2010—2026 历年真题,含答案与解析;已入库 SQLite 题库 `题库/zhenti_kaodian.db`,共 544 题)。以下收录本专题对应考点的全部历年真题,按年份排序,可直接闭卷刷。",
"",
]
for i, q in enumerate(qs, 1):
qtype = "多选" if q["type"] == "多选" else "单选"
lines.append(f"**{i}. {q['year']}-{q['qno']} {qtype} · {q['kp']}**")
lines.append(q["stem"])
if q["opts"]:
lines.append(fmt_options(q["opts"]))
note = f" {q['note']}" if q["note"] else ""
lines.append(f"**答案 {q['answer']}**{note}|**解析**:{fmt_analysis(q['analysis'])}")
lines.append(f"> 原题出处:{q['url']}")
lines.append("")
return "\n".join(lines)
def main():
qs = load_questions()
by_topic = {}
for q in qs:
t = TOPIC_MAP.get(q["kp"])
if t is None:
print(f"!! 未映射考点: {q['kp']}", flush=True)
continue
by_topic.setdefault(t, []).append(q)
report = []
total_chars = 0
for t in range(1, 10):
path = os.path.join(NOTE_DIR, f"专题{t} 某某.md")
# 实际文件名按目录列出
# 直接用 glob 找文件
import glob
files = {int(m.group(1)): m.group(0) for m in
(re.match(r"专题(\d+) (.+?)\.md", os.path.basename(p)) for p in
glob.glob(os.path.join(NOTE_DIR, "专题*.md"))) if m}
for t in sorted(files):
fname = files[t]
path = os.path.join(NOTE_DIR, fname)
text = open(path, encoding="utf-8").read()
sec = build_section(by_topic.get(t, []))
if not sec:
report.append(f"{fname}: 无真题,跳过")
continue
anchor = "## 三、易混点速查"
if anchor not in text:
report.append(f"{fname}: 未找到锚点 {anchor},跳过")
continue
# 幂等: 移除已存在的旧真题精练区再重建
m = re.search(r"### 真题精练.*?(?=\n## 三、)", text, re.S)
if m:
text = text[: m.start()] + text[m.end():]
text = text.replace(anchor, sec + "\n\n" + anchor, 1)
open(path, "w", encoding="utf-8").write(text)
nq = len(by_topic.get(t, []))
nchars = len(text)
total_chars += nchars
report.append(f"{fname}: 插入 {nq} 题,文件 {nchars} 字符")
report.append(f"马原 9 专题共 {len(qs)} 真题,合计约 {total_chars} 字符")
out = os.path.join(HERE, "_gen_report.txt")
open(out, "w", encoding="utf-8").write("\n".join(report))
print("\n".join(report), flush=True)
if __name__ == "__main__":
main()