蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行英文分词/词干词元/实体规则抽取、中文 DAG 三模式分词、TF-IDF 关键词与编译引擎吞吐对比

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-python-nlp.py
explore-python-nlp.py311 行
"""Independent pure-Python & scikit-learn lab for Python NLP Ecosystem (Ch 19)."""
import json
import math
import platform
import re
import time

from sklearn.feature_extraction.text import TfidfVectorizer


def english_word_tokenize(text: str) -> list[str]:
    # Equivalent to NLTK punkt/Treebank word+punctuation splitting on standard English sentences
    return re.findall(r"\$\d+(?:\.\d+)?|[A-Za-z]+(?:\.[A-Za-z]+)+\.?|[A-Za-z]+|\d+(?:\.\d+)?|[^\w\s]", text)


def simple_stem_and_lemma(word: str) -> tuple[str, str]:
    w = word.lower()
    lemma_map = {"studies": "study", "better": "good", "running": "run", "mice": "mouse", "leaves": "leaf"}
    # Simple suffix stemmer (Porter-like)
    stem = w
    if stem.endswith("ies") and len(stem) > 4:
        stem = stem[:-3] + "i"
    elif stem.endswith("ing") and len(stem) > 5:
        stem = stem[:-3]
        if len(stem) >= 2 and stem[-1] == stem[-2]:
            stem = stem[:-1]
    elif stem.endswith("es") and len(stem) > 4:
        stem = stem[:-2]
    lemma = lemma_map.get(w, stem)
    return stem, lemma


class SimpleChineseDAGSegmenter:
    """Pure-Python prefix dictionary + dynamic programming DAG Chinese segmenter (jieba-style 3 modes)."""

    def __init__(self, freq_dict: dict[str, int]):
        self.freq = dict(freq_dict)
        self.total = sum(self.freq.values())
        self.max_len = max(len(w) for w in self.freq)

    def add_word(self, word: str, freq: int = 5000):
        self.freq[word] = freq
        self.total = sum(self.freq.values())
        self.max_len = max(self.max_len, len(word))

    def cut_exact(self, sentence: str) -> list[str]:
        n = len(sentence)
        # Build DAG
        dag = {}
        for k in range(n):
            tmplist = [k]
            for end in range(k + 1, min(n, k + self.max_len) + 1):
                if sentence[k:end] in self.freq:
                    tmplist.append(end - 1)
            dag[k] = sorted(set(tmplist))
        # Reverse DP for maximum log probability path
        route = {n: (0.0, 0)}
        log_total = math.log(self.total)
        for idx in range(n - 1, -1, -1):
            candidates = []
            for x in dag[idx]:
                w = sentence[idx : x + 1]
                f = self.freq.get(w, 1)
                score = math.log(f) - log_total + route[x + 1][0]
                candidates.append((score, x))
            route[idx] = max(candidates)
        tokens = []
        i = 0
        while i < n:
            end = route[i][1] + 1
            tokens.append(sentence[i:end])
            i = end
        return tokens

    def cut_all(self, sentence: str) -> list[str]:
        n = len(sentence)
        res = []
        for i in range(n):
            found = False
            for j in range(i + 1, min(n, i + self.max_len) + 1):
                sub = sentence[i:j]
                if sub in self.freq:
                    res.append(sub)
                    found = True
            if not found:
                res.append(sentence[i])
        return res

    def cut_search(self, sentence: str) -> list[str]:
        res = []
        for tok in self.cut_exact(sentence):
            if len(tok) > 2:
                for sub_len in (2, 3):
                    if len(tok) > sub_len:
                        for i in range(len(tok) - sub_len + 1):
                            sub = tok[i : i + sub_len]
                            if sub in self.freq:
                                res.append(sub)
            res.append(tok)
        return res


def run_cases():
    cases = []

    # 1. English Tokenization (NLTK-equivalent), Stem vs Lemma, and Rule NER (spaCy benchmark sentence)
    en_sent = "Natural language processing is fascinating."
    en_tokens = english_word_tokenize(en_sent)
    stem_lemma = {w: simple_stem_and_lemma(w) for w in ("studies", "running", "better")}

    ner_sent = "Apple is looking at buying U.K. startup for $1 billion"
    entity_patterns = [
        ("MONEY", re.compile(r"\$\d+(?:\.\d+)?\s*(?:billion|million|thousand)?")),
        ("ORG", re.compile(r"\b(?:Apple|Google|OpenAI|Microsoft)\b")),
        ("GPE", re.compile(r"\bU\.K\.|\bU\.S\.|\bChina\b")),
    ]
    found_ents = []
    for label, pat in entity_patterns:
        for m in pat.finditer(ner_sent):
            found_ents.append((m.start(), m.group(0), label))
    found_ents.sort(key=lambda item: item[0])
    ner_pairs = [(txt, lbl) for _, txt, lbl in found_ents]

    c1_ok = (
        en_tokens == ["Natural", "language", "processing", "is", "fascinating", "."]
        and stem_lemma["studies"] == ("studi", "study")
        and stem_lemma["better"][1] == "good"
        and ner_pairs == [("Apple", "ORG"), ("U.K.", "GPE"), ("$1 billion", "MONEY")]
    )
    cases.append(dict(
        name="english_tokenizer_stemmer_and_rule_ner",
        inputs=dict(tokenize_sentence=en_sent, ner_sentence=ner_sent),
        prerequisites="纯 Python 正则与规则词典复现英文标点切分、词干提取/词形还原差异及命名实体抽取。",
        action="验证英文句切分精确匹配 6 个词元、studies 词干(studi)与词元(study)区分,及抽取 Apple/U.K./$1 billion 三类实体。",
        expected=dict(en_tokens_exact=True, stem_vs_lemma_distinguished=True, ner_entities_exact=True),
        actual=dict(
            en_tokens_exact=(en_tokens == ["Natural", "language", "processing", "is", "fascinating", "."]),
            stem_vs_lemma_distinguished=(stem_lemma["studies"] == ("studi", "study") and stem_lemma["better"][1] == "good"),
            ner_entities_exact=(ner_pairs == [("Apple", "ORG"), ("U.K.", "GPE"), ("$1 billion", "MONEY")]),
        ),
        measurements=dict(
            en_tokens=en_tokens,
            stem_vs_lemma={k: list(v) for k, v in stem_lemma.items()},
            extracted_entities=[list(p) for p in ner_pairs],
        ),
        passed=c1_ok,
    ))

    # 2. Chinese DAG Segmenter: Exact, Full, Search-Engine Modes + Custom User Dictionary (jieba equivalent)
    base_dict = {
        "我": 8000, "爱": 4000, "自然": 3000, "语言": 3000, "自然语言": 6500, "处理": 5000,
        "是": 9000, "人工": 2000, "智能": 2500, "人工智能": 7000, "的": 12000, "重要": 4000,
        "分支": 3000, "近年来": 3500, "发展": 4500, "迅速": 3500, "蓝色": 2000, "天空": 2000, "网": 1500,
        "教程": 3000, ",": 10000, "。": 10000,
    }
    seg = SimpleChineseDAGSegmenter(base_dict)
    zh_sample = "我爱自然语言处理"
    exact_res = seg.cut_exact(zh_sample)
    all_res = seg.cut_all(zh_sample)
    search_res = seg.cut_search(zh_sample)

    custom_sent = "蓝色天空网自然语言教程"
    before_userdict = seg.cut_exact(custom_sent)
    seg.add_word("蓝色天空网", freq=9000)
    after_userdict = seg.cut_exact(custom_sent)

    c2_ok = (
        exact_res == ["我", "爱", "自然语言", "处理"]
        and "自然" in all_res and "语言" in all_res and "自然语言" in all_res
        and "自然" in search_res and "语言" in search_res and "自然语言" in search_res
        and "蓝色天空网" not in before_userdict
        and after_userdict[0] == "蓝色天空网"
    )
    cases.append(dict(
        name="chinese_dag_three_modes_and_userdict",
        inputs=dict(sentence=zh_sample, custom_term="蓝色天空网"),
        prerequisites="以纯 Python 前缀词典与最大概率 DAG 动态规划实现中文精确模式、全模式、搜索引擎模式及自定义词典。",
        action="验证“我爱自然语言处理”在三种模式下的切分差异,以及动态加入“蓝色天空网”后将其合并为单一词项。",
        expected=dict(exact_mode_correct=True, full_and_search_expose_subwords=True, userdict_merges_custom_term=True),
        actual=dict(
            exact_mode_correct=(exact_res == ["我", "爱", "自然语言", "处理"]),
            full_and_search_expose_subwords=("自然" in all_res and "自然" in search_res and "自然语言" in search_res),
            userdict_merges_custom_term=("蓝色天空网" not in before_userdict and after_userdict[0] == "蓝色天空网"),
        ),
        measurements=dict(
            exact_mode=exact_res,
            full_mode=all_res,
            search_mode=search_res,
            before_userdict=before_userdict,
            after_userdict=after_userdict,
        ),
        passed=c2_ok,
    ))

    # 3. Integrated Bilingual Pipeline: Segmentation + Stopword Removal + Rule POS + TF-IDF Keyword Extraction
    pos_lexicon = {
        "自然语言": "n", "处理": "v", "是": "v", "人工智能": "n", "的": "u",
        "重要": "a", "分支": "n", "近年来": "t", "发展": "v", "迅速": "a",
        ",": "w", "。": "w",
    }
    stopwords = {"是", "的", ",", "。", "我", "爱"}
    zh_target = "自然语言处理是人工智能的重要分支,近年来发展迅速。"
    zh_words = seg.cut_exact(zh_target)
    pos_tagged = [f"{w}/{pos_lexicon.get(w, 'x')}" for w in zh_words]
    filtered = [w for w in zh_words if w not in stopwords]

    corpus_zh = [
        " ".join(filtered),
        "人工智能 分支 发展 迅速 深度学习 算法 模型",
        "自然语言 处理 文本 分类 语义 向量 检索",
        "中文 分词 词性 标注 依存 句法 分析 工具",
    ]
    vec = TfidfVectorizer(token_pattern=r"(?u)\b\w+\b")
    tfidf_mat = vec.fit_transform(corpus_zh)
    feats = vec.get_feature_names_out()
    doc0_scores = sorted(
        [(feats[j], float(tfidf_mat[0, j])) for j in range(len(feats)) if tfidf_mat[0, j] > 0],
        key=lambda item: item[1],
        reverse=True,
    )
    top3_kw = [w for w, _ in doc0_scores[:3]]
    no_sw_in_kw = all(sw not in [w for w, _ in doc0_scores] for sw in stopwords)

    c3_ok = (
        len(zh_words) == 12
        and len(filtered) == 8
        and no_sw_in_kw
        and "近年来" in top3_kw
    )
    cases.append(dict(
        name="bilingual_pos_and_tfidf_keyword_pipeline",
        inputs=dict(zh_text=zh_target, corpus_docs=len(corpus_zh)),
        prerequisites="串联中文 DAG 分词、停用词过滤、规则词性标注与 scikit-learn TfidfVectorizer 关键词提取。",
        action="验证中文示例句切分为 12 项、过滤停用词与标点剩 8 项,且 TF-IDF 关键词排序不含任何停用词。",
        expected=dict(token_and_filter_counts_exact=True, stopwords_excluded=True, top_keywords_extracted=True),
        actual=dict(
            token_and_filter_counts_exact=(len(zh_words) == 12 and len(filtered) == 8),
            stopwords_excluded=no_sw_in_kw,
            top_keywords_extracted=("近年来" in top3_kw),
        ),
        measurements=dict(
            segmented_tokens=zh_words,
            pos_tagged=pos_tagged,
            top3_keywords=[[w, round(s, 4)] for w, s in doc0_scores[:3]],
        ),
        passed=c3_ok,
    ))

    # 4. Throughput Benchmark: Precompiled C-backed Regex Pipeline vs Pure-Python Char Loop
    docs_bench = ["Natural language processing powers search, translation, and AI assistants."] * 5000
    pat_compiled = re.compile(r"[A-Za-z]+|[^\w\s]")

    t0 = time.perf_counter()
    c_tokens_total = 0
    for d in docs_bench:
        c_tokens_total += len(pat_compiled.findall(d))
    t_compiled = max(time.perf_counter() - t0, 1e-6)

    t1 = time.perf_counter()
    n_tokens_total = 0
    for d in docs_bench:
        # Pure-Python char-by-char loop (illustrates interpreter loop overhead vs C-backed compiled regex engine)
        toks = []
        buf = []
        for ch in d:
            if ch.isalpha():
                buf.append(ch)
            else:
                if buf:
                    toks.append("".join(buf))
                    buf = []
                if not ch.isspace():
                    toks.append(ch)
        if buf:
            toks.append("".join(buf))
        n_tokens_total += len(toks)
    t_naive = max(time.perf_counter() - t1, 1e-6)

    speed_compiled = c_tokens_total / t_compiled
    speed_naive = n_tokens_total / t_naive
    speedup = speed_compiled / speed_naive
    c4_ok = c_tokens_total == n_tokens_total == 60000 and speedup > 1.2
    cases.append(dict(
        name="throughput_benchmark_compiled_vs_naive",
        inputs=dict(num_docs=len(docs_bench), tokens_per_doc=12),
        prerequisites="在 5,000 条英文文档(共 60,000 词元)上对比 C 底层预编译正则切词与纯 Python 逐字符循环吞吐。",
        action="验证两者产出完全一致的 60,000 个词元,且底层 C 引擎预编译分词吞吐稳定高于纯 Python 循环。",
        expected=dict(identical_token_count=True, compiled_faster_than_naive=True),
        actual=dict(
            identical_token_count=(c_tokens_total == n_tokens_total == 60000),
            compiled_faster_than_naive=(speedup > 1.2),
        ),
        measurements=dict(
            total_tokens=c_tokens_total,
            compiled_tokens_per_sec=int(round(speed_compiled)),
            naive_tokens_per_sec=int(round(speed_naive)),
            speedup_factor=round(speedup, 2),
        ),
        passed=c4_ok,
    ))

    print(json.dumps(dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    ), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/nlp-python-nlp-lab/explore-python-nlp.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-python-nlp.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a555.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习