# -*- coding: utf-8 -*-
import io, sys, os, re, html, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
B = r"D:\work buddy\2026-11-05-14-15-52"
h = open(os.path.join(B,"raw_ucsd.html"),encoding="utf-8").read()
i = h.find("<h1>Graduate Degrees")
seg = h[i:]

DEG_TOKENS = ["PhD","MS","MEng","MA","MFA","MPH","MPP","MAS","MPS","MBA","MD","JD","AuD","EdD","EdS",
 "MSW","MIA","MArch","MES","MFin","MSI","MDes","MDS","MQF","MPAc","MURP","MCEPA","MCPA","DMA","MEd","MLIS",
 "MSPH","DrPH","MSES","MCMP","M.S.","M.A.","M.Eng.","Ph.D.","MFA.",]
FOOTER = {"Accessibility","Privacy","Terms of Use","Feedback"}

blocks = re.split(r"<h4[^>]*>(.*?)</h4>", seg, flags=re.S)
rows=[]; college=None
for k,blk in enumerate(blocks):
    if k==0: continue
    if k%2==1:
        college=html.unescape(re.sub(r"<[^>]+>","",blk)).strip()
    else:
        for li in re.findall(r"<li[^>]*>(.*?)</li>", blk, re.S):
            txt=html.unescape(re.sub(r"<[^>]+>","",li)).replace("\xa0"," ").strip()
            txt=txt.rstrip("*†‡ ").strip()
            if txt in FOOTER: continue
            degs=[]; name=txt
            # 反复剥离尾部学位 token
            changed=True
            while changed:
                changed=False
                for tok in sorted(DEG_TOKENS,key=len,reverse=True):
                    m=re.search(r"(?:,|\s)+"+re.escape(tok)+r"\s*$", name, re.I)
                    if m:
                        degs.append(tok); name=name[:m.start()].rstrip(", ").strip(); changed=True; break
            rows.append({"college":college,"name":name,"deg":",".join(degs),"raw":txt})

json.dump(rows, open(os.path.join(B,"raw_ucsd.json"),"w",encoding="utf-8"), ensure_ascii=False, indent=1)
print("条目:", len(rows))
from collections import Counter
print("学位:", dict(Counter(r["deg"] for r in rows)))
# 未识别学位的
for r in rows:
    if not r["deg"]: print("  未识别:", r["college"][:20], "|", r["raw"])
