"""
=============================================================================
CMU 11-642 · 第 1 讲共享模块：text_tools.py —— 从文本到词项：分词、停用词、词干，以及文本的统计规律
=============================================================================

【这个模块是干什么的】
    搜索引擎看不到"意思"，只看到一串字符。建索引之前，先要把文本变成一串**词项**（term）：
        "The Jaguars hunted near the river."
          → 分词 tokenize   ["the", "jaguars", "hunted", "near", "the", "river"]
          → 去停用词 stop   [        "jaguars", "hunted", "near",        "river"]   （位置保留空洞）
          → 词干 stem      [        "jaguar",  "hunted", "near",        "river"]
    这一串处理叫"分析"（analysis，Lucene 的叫法），第 8 讲会仔细比较各种做法；
    第 1 讲只用最简单的一套：小写 + 按非字母数字切分 + Lucene 的 33 个英文停用词 + Harman 的 S 词干。

    模块的后半部分是第 1 讲 §3 的文本统计工具：词频表、Zipf 定律和 Heaps 定律的拟合，
    以及一份"真实文本"——你电脑上 Python 标准库里的文档字符串（docstring）。

【主要接口 API】
    tokenize(text)                    小写，切出 [a-z0-9]+ 的词
    LUCENE_STOPWORDS                  Lucene 默认的 33 个英文停用词
    s_stem(word)                      Harman (1991) 的 S 词干：只处理复数
    Analyzer(stopwords, stem)         一套完整的分析流程；analyze(text) → [(词项, 位置), ...]
    term_counts(token_lists)          词 → 出现次数
    rank_frequency(counts)            按次数从大到小排好的 [(词, 次数), ...]
    fit_loglog(xs, ys)                在双对数坐标上做最小二乘直线拟合 → (斜率, 截距)
    heaps_points(token_lists, k)      (已读词数, 词表大小) 的增长曲线
    stdlib_docstrings()               本机 Python 标准库的文档字符串（真实英文文本）

【运行方式】
    python3 text_tools.py     # 自检：分词、S 词干的例子；停用词表；真实文本有多少词（约 3 秒）
"""

import ast
import math
import os
import re
import sys
import sysconfig
import warnings


# ---------------------------------------------------------------------------
# 1. 分词、停用词、词干
# ---------------------------------------------------------------------------

_TOKEN_RE = re.compile(r"[a-z0-9]+")


def tokenize(text):
    """
    最简单的分词器：先转小写，再切出所有连续的字母数字串。

    【思路】空格、标点、连字符都当作分隔符："two-factor" → ["two", "factor"]，
        "page.php?id=42" → ["page", "php", "id", "42"]，"401k" → ["401k"]。
    【参数】text：字符串
    【返回】词的列表（保持原文顺序）
    【边界】非 ASCII 字母会被当作分隔符丢掉（"café" → ["caf"]）；撇号会把词切开
        （"don't" → ["don", "t"]）。英文玩具网络里这些情况很少，第 8 讲专门讨论更好的分词。
    【Python 小知识】re.compile 先把正则表达式编译好，反复使用时更快；
        findall 返回所有不重叠匹配的列表。
    """
    return _TOKEN_RE.findall(text.lower())


# Lucene（Elasticsearch、Solr 的底层库）默认的英文停用词表，一共 33 个。
# 很多引擎的停用词表比这长得多（几百个），也有很多现代引擎根本不删停用词——第 8 讲讨论为什么。
LUCENE_STOPWORDS = frozenset([
    "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it",
    "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they",
    "this", "to", "was", "will", "with",
])


def s_stem(word):
    """
    Harman (1991) 的 S 词干器（S-stemmer）：只去掉英文名词的复数词尾，按顺序只用第一条适用的规则。

    【思路】三条规则：
        1. 以 "ies" 结尾、但不以 "eies" 或 "aies" 结尾 → 把 "ies" 换成 "y"     （berries → berry）
        2. 以 "es" 结尾、但不以 "aes"、"ees"、"oes" 结尾 → 把 "es" 换成 "e"  （boxes → boxe ⚠）
        3. 以 "s" 结尾、但不以 "us" 或 "ss" 结尾 → 去掉 "s"                  （jaguars → jaguar）
        它很"保守"：只合并单复数，几乎不会把意思不同的词合并到一起（Porter 词干器会把 "university"
        和 "universe" 都变成 "univers"）。代价是有些单复数合不上：box → "box"，boxes → "boxe"。
    【参数】word：小写的词
    【返回】词干（不一定是真实的英文词，只要"同一个词的不同形式变成同一个串"就行）
    【边界】很短的词（≤ 3 个字母）不处理，避免 "gas" → "ga"、"bus" 本来就被规则 3 排除。
        专有名词也会被处理：Mars → "mar"——查询和文档用同一个词干器，所以照样能匹配上。
    【检索联系】词干处理提高召回率（jaguar 也能找到写 jaguars 的文档），但可能降低精确率；
        第 8 讲比较 S、Porter、Krovetz 三种词干器。
    """
    if len(word) <= 3:
        return word
    if word.endswith("ies") and not word.endswith(("eies", "aies")):
        return word[:-3] + "y"
    if word.endswith("es") and not word.endswith(("aes", "ees", "oes")):
        return word[:-1]
    if word.endswith("s") and not word.endswith(("us", "ss")):
        return word[:-1]
    return word


class Analyzer:
    """
    一套完整的文本分析流程：分词 → （去停用词）→ （词干）。建索引和处理查询必须用**同一个** Analyzer，
    否则 "Jaguars" 在索引里是 "jaguar"、在查询里是 "jaguars"，永远匹配不上。

    【参数】
        stopwords：停用词集合（默认 Lucene 的 33 个；传 None 或空集合表示不删停用词）
        stem：None（不做词干）或 "s"（S 词干）
    【位置的约定】位置按**分词后**的词数计算，停用词被删掉后留下"空洞"：
        "the black hole" → [("black", 1), ("hole", 2)]——位置 0 的 "the" 没了，但 black 仍在位置 1。
        Lucene 默认也是这样（position increment）。好处："black hole" 和 "black the hole"
        在去停用词之后仍然是不同的距离，#NEAR/1(black hole) 不会把后者当成短语。
    【Python 小知识】self._cache 是一个字典，记住每个词处理后的结果：同一个词在一万篇文档里出现
        几万次，词干只算一次。
    """

    def __init__(self, stopwords=LUCENE_STOPWORDS, stem="s"):
        if stem not in (None, "s"):
            raise ValueError("stem 只能是 None 或 's'（第 8 讲会加入更多词干器）")
        self.stopwords = frozenset(stopwords or ())
        self.stem = stem
        self._cache = {}

    def describe(self):
        """一句话描述这套分析流程（打印实验配置时用）。"""
        parts = ["小写 + [a-z0-9]+ 分词"]
        parts.append("去 %d 个停用词" % len(self.stopwords) if self.stopwords else "不去停用词")
        parts.append("S 词干" if self.stem == "s" else "不做词干")
        return "，".join(parts)

    def normalize(self, token):
        """
        一个已经分好、小写的词 → 词项；停用词返回 None。

        【边界】空字符串返回 None。
        """
        r = self._cache.get(token, False)
        if r is not False:
            return r
        if not token or token in self.stopwords:
            r = None
        elif self.stem == "s":
            r = s_stem(token)
        else:
            r = token
        self._cache[token] = r
        return r

    def analyze(self, text):
        """
        文本 → [(词项, 位置), ...]。

        【返回】列表；位置从 0 开始，停用词的位置被跳过（留下空洞），见类的说明。
        """
        out = []
        norm = self.normalize
        for pos, tok in enumerate(tokenize(text)):
            t = norm(tok)
            if t is not None:
                out.append((t, pos))
        return out

    def terms(self, text):
        """只要词项、不要位置：文本 → [词项, ...]。"""
        return [t for t, _ in self.analyze(text)]


# ---------------------------------------------------------------------------
# 2. 文本统计：词频、Zipf、Heaps
# ---------------------------------------------------------------------------

def term_counts(token_lists):
    """
    统计每个词出现了多少次。

    【参数】token_lists：可迭代对象，每个元素是一篇文档的词列表
    【返回】(counts, n_tokens)：counts = {词: 次数}；n_tokens = 总词数
    【Python 小知识】dict.get(k, 0) 在 k 不存在时返回 0，这样不用先判断 "if k in counts"。
        collections.Counter 也能做这件事；这里手写是为了让每一步都看得见。
    """
    counts = {}
    n = 0
    for toks in token_lists:
        n += len(toks)
        for t in toks:
            counts[t] = counts.get(t, 0) + 1
    return counts, n


def rank_frequency(counts):
    """
    把词按出现次数从大到小排好：[(词, 次数), ...]。次数相同的按字母顺序（保证结果确定、可复现）。

    【Python 小知识】sorted(..., key=lambda kv: (-kv[1], kv[0]))：先按次数的相反数（即从大到小），
        再按词本身排序。lambda 是一个没有名字的小函数。
    """
    return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))


def fit_loglog(xs, ys):
    """
    在双对数坐标上做最小二乘直线拟合：log10(y) ≈ 斜率 × log10(x) + 截距。

    【思路】幂律 y = C·x^a 取对数后是一条直线 log y = a·log x + log C，斜率就是指数 a。
        Zipf 定律（频率 ∝ 排名^(−1)）和 Heaps 定律（词表大小 ∝ 词数^β）都是幂律，
        所以都可以用这个函数估计指数。
    【参数】xs、ys：正数列表，长度相同且至少 2 个点
    【返回】(斜率, 截距)，截距是 log10(C)
    【边界】x 或 y 不是正数时取对数会出错，直接抛出 ValueError。
        双对数最小二乘会被尾部大量"次数 = 1"的点拉偏（Clauset et al. 2009 讨论过更好的估计方法）；
        这里只用它看大致的斜率，所以拟合时通常只取中间一段排名（见 02 号脚本）。
    """
    if len(xs) != len(ys) or len(xs) < 2:
        raise ValueError("需要至少两个点，且 xs、ys 等长")
    lx = [math.log10(x) for x in xs]
    ly = [math.log10(y) for y in ys]
    n = len(lx)
    mx = math.fsum(lx) / n
    my = math.fsum(ly) / n
    sxx = math.fsum((a - mx) ** 2 for a in lx)
    sxy = math.fsum((a - mx) * (b - my) for a, b in zip(lx, ly))
    slope = sxy / sxx
    return slope, my - slope * mx


def heaps_points(token_lists, n_points=12):
    """
    Heaps 定律的增长曲线：依次读入文档，记录"读了多少词"时"见过多少个不同的词"。

    【参数】token_lists：文档的词列表构成的列表（按顺序读）；n_points：在对数均匀的位置记录几个点
    【返回】[(已读词数 T, 词表大小 M), ...]，T 从小到大
    【边界】总词数很少（< 100）时点会重复，函数会去掉重复的 T。
    """
    total = sum(len(t) for t in token_lists)
    if total == 0:
        return []
    marks = sorted({max(1, int(round(total ** (k / (n_points - 1))))) for k in range(n_points)})
    seen = set()
    out = []
    n = 0
    mi = 0
    for toks in token_lists:
        for t in toks:
            seen.add(t)
            n += 1
            while mi < len(marks) and n >= marks[mi]:
                out.append((n, len(seen)))
                mi += 1
    return out


# ---------------------------------------------------------------------------
# 3. 一份真实文本：本机 Python 标准库的文档字符串
# ---------------------------------------------------------------------------

def stdlib_docstrings(limit_files=None):
    """
    收集本机 Python 标准库里所有模块、类、函数的文档字符串（docstring）——一份真实的英文技术文本。

    【为什么用它】讲 Zipf 定律时，用我们自己生成的玩具网络去"验证"Zipf 定律是循环论证
        （生成器就是按 Zipf 分布写的）。真实文本才能说明这个规律真的存在。标准库随 Python 一起安装，
        不需要下载任何东西；缺点是它的内容随 Python 版本变化，所以这部分数字和讲义可能略有不同。
    【参数】limit_files：最多读多少个 .py 文件（None 表示全部；冒烟测试时可以设小一点）
    【返回】(docstrings, info)：docstrings 是字符串列表（按文件路径排序，结果确定）；
        info = {"python": 版本号, "files": 读了几个文件, "root": 标准库路径}
    【边界】跳过测试目录（test、tests、idle_test）和第三方包目录（site-packages）；
        解析失败的文件（极少数故意写错语法的测试数据）直接跳过；
        解析时关掉警告（Python 3.12 起，旧文件里的无效转义序列会触发 SyntaxWarning，
        用 python3 -W error 运行时警告会变成错误）。
    【Python 小知识】ast（抽象语法树）模块把源代码解析成树；ast.get_docstring(节点) 取出
        模块 / 类 / 函数开头的那个字符串。os.walk 递归地列出一个目录下的所有文件。
    """
    root = sysconfig.get_paths()["stdlib"]
    skip_dirs = {"test", "tests", "idle_test", "site-packages", "__pycache__", "lib2to3"}
    paths = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(d for d in dirnames if d not in skip_dirs)
        for fn in sorted(filenames):
            if fn.endswith(".py"):
                paths.append(os.path.join(dirpath, fn))
    paths.sort()
    if limit_files is not None:
        paths = paths[:limit_files]
    docs = []
    nfiles = 0
    for p in paths:
        try:
            with open(p, encoding="utf-8") as fh:
                src = fh.read()
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                tree = ast.parse(src)
        except (SyntaxError, UnicodeDecodeError, ValueError):
            continue
        nfiles += 1
        for node in ast.walk(tree):
            if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
                ds = ast.get_docstring(node)
                if ds:
                    docs.append(ds)
    info = {"python": "%d.%d.%d" % sys.version_info[:3], "files": nfiles, "root": root}
    return docs, info


# ---------------------------------------------------------------------------
# 4. 自检
# ---------------------------------------------------------------------------

def _self_test():
    from console import print_header, print_table

    print_header("分词与 S 词干")
    s = "The Jaguars hunted near the river; two-factor log-in at page.php?id=42 (401k plans)."
    print("  原文：", s)
    print("  tokenize：", tokenize(s))
    a = Analyzer()
    print("  Analyzer（%s）：" % a.describe())
    print("   ", a.analyze(s))
    rows = [[w, s_stem(w)] for w in ["jaguars", "berries", "boxes", "glasses", "species", "mars", "bus",
                                     "classes", "news", "series", "toes", "is"]]
    print_table(["词", "S 词干"], rows)
    assert s_stem("jaguars") == "jaguar" and s_stem("berries") == "berry" and s_stem("glass") == "glass"

    print_header("Lucene 的 33 个英文停用词")
    print("  " + " ".join(sorted(LUCENE_STOPWORDS)))

    print_header("真实文本：本机 Python 标准库的文档字符串")
    docs, info = stdlib_docstrings()
    toks = [tokenize(d) for d in docs]
    n = sum(len(t) for t in toks)
    print("  Python %s：%d 个文件，%d 段文档字符串，%d 个词" % (info["python"], info["files"], len(docs), n))


if __name__ == "__main__":
    _self_test()
