# -*- coding: utf-8 -*-
import io, sys, re, html as H
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

b = open("_cornell_mse_raw.html", "rb").read().decode("utf-8", "ignore")
# 去脚本样式
t = re.sub(r"<script.*?</script>", " ", b, flags=re.S)
t = re.sub(r"<style.*?</style>", " ", t, flags=re.S)
t = H.unescape(re.sub(r"<[^>]+>", " ", t))
t = re.sub(r"[ \t]+", " ", t)
t = re.sub(r"\n\s*\n+", "\n", t)
open("_cornell_mse.txt", "w", encoding="utf-8").write(t)

# 链接矩阵
links = re.findall(r'href="([^"]+)"', b)
mse_links = sorted(set(l for l in links if "mse" in l.lower() or "meng" in l.lower()))
print("=== MSE 相关链接 ===")
for l in mse_links:
    print(l)

print("\n=== 正文关键词切片 ===")
for kw in ["Master of Engineering", "M.Eng", "credit", "Focus", "track", "concentration",
           "deadline", "Fall", "Spring", "recommend", "GRE", "prerequisite", "STEM",
           "OPT", "tuition", "degree requirement", "On-Campus", "Distance", "Project",
           "Biomedical", "Computational", "Energy", "Materials", "career", "employment"]:
    idx = 0
    cnt = 0
    while True:
        i = t.lower().find(kw.lower(), idx)
        if i < 0 or cnt >= 2:
            break
        print(f"\n--- [{kw}] @{i} ---")
        print(t[max(0, i-180):i+320].strip())
        idx = i + len(kw)
        cnt += 1
