"""從考選部律師考試 PDF 產生 exam_675.csv。 用法(需要 poppler 的 pdftotext,macOS: brew install poppler): python3 build_exam_csv.py <輸出 csv> 選項代號 A–D 在 PDF 內是私有區字元 U+E18C–U+E18F,pdftotext 會原樣保留, 用它定位選項,選項換行時尾巴會接回原選項。 """ import csv import re import subprocess import sys import tempfile from pathlib import Path MARK = {"": "A", "": "B", "": "C", "": "D"} MARK_RE = re.compile("([-])") HEADER_RE = re.compile(r"^\s*(代號:|頁次:|\d+年.*(考試|試題)|第一試|類\s+科|科\s+目|考試時間|※注意|\s*[㈠㈡㈢]|本試題|禁止使用)") QSTART_RE = re.compile(r"^\s{0,3}(\d{1,3})\s{2,}(\S.*)$") SUBJECTS = { "1301": "綜合法學(刑法、刑事訴訟法、法律倫理)", "3301": "綜合法學(民法、民事訴訟法)", "4301": "綜合法學(公司法、保險法、票據法、證券交易法、強制執行法、法律倫理)", } DECLARED = {"1301": 75, "3301": 80, "4301": 70} # 答案 PDF 上的單選題數 def pdf_text(pdf: Path) -> str: out = subprocess.run(["pdftotext", "-layout", str(pdf), "-"], check=True, capture_output=True, text=True) return out.stdout def parse_questions(text: str): qs, cur, opt = [], None, None for raw in text.split("\n"): line = raw.rstrip() if not line.strip(): continue if MARK_RE.search(line) is None: m = QSTART_RE.match(line) if m and not HEADER_RE.match(line): cur = {"q_num": int(m.group(1)), "stem": m.group(2).strip(), "opts": {}} qs.append(cur) opt = None continue if HEADER_RE.match(line) or cur is None: continue if opt: cur["opts"][opt] += line.strip() else: cur["stem"] += line.strip() continue parts = MARK_RE.split(line) for i in range(1, len(parts), 2): opt = MARK[parts[i]] cur["opts"][opt] = cur["opts"].get(opt, "") + parts[i + 1].strip() return qs def parse_answers(text: str): ans = {} lines = text.split("\n") for i, line in enumerate(lines): nums = re.findall(r"第\s*(\d+)\s*題", line) if nums and i + 1 < len(lines) and lines[i + 1].lstrip().startswith("答案"): for n, v in zip(nums, lines[i + 1].split()[1:]): ans[int(n)] = v return ans def main(pdf_dir: Path, out: Path): rows = [] for qpdf in sorted((pdf_dir / "questions").glob("*.pdf")): exam, subj = qpdf.stem.split("_") # 例:108120_1301 year, batch = exam[:3], exam[3:] apdf = pdf_dir / "answers" / f"{exam}_ANS{subj}.pdf" qs, ans = parse_questions(pdf_text(qpdf)), parse_answers(pdf_text(apdf)) nums = [q["q_num"] for q in qs] assert nums == list(range(1, DECLARED[subj] + 1)), f"{qpdf.name}: 題號不連續或題數與答案 PDF 不符" assert sorted(ans) == nums, f"{qpdf.name}: 答案題號與題目不一致" for q in qs: assert sorted(q["opts"]) == list("ABCD"), f"{qpdf.name} 第 {q['q_num']} 題選項不是 A–D" assert ans[q["q_num"]] in "ABCD", f"{qpdf.name} 第 {q['q_num']} 題答案不是單一選項" text = q["stem"] + "".join(f"\n{o}. {q['opts'][o]}" for o in "ABCD") rows.append({ "qid": f"{exam}_{subj}_q{q['q_num']}", "year": year, "batch": batch, "subject_code": subj, "subject_name": SUBJECTS[subj], "q_num": q["q_num"], "q_text": text, "correct_answer": ans[q["q_num"]], }) with out.open("w", encoding="utf-8", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0])) w.writeheader() w.writerows(rows) print(f"wrote {len(rows)} rows -> {out}") if __name__ == "__main__": main(Path(sys.argv[1]), Path(sys.argv[2]))