Python NLP 生态
核对 NLTK、spaCy、jieba 与 HanLP 四大 Python NLP 工具的定位、功能与选型对比,纠正 HanLP 1.x/2.x 接口与 NLTK punkt_tab 变化,并以纯 Python+scikit-learn 实测英文分词/NER、中文 DAG 三模式分词与 TF-IDF 关键词提取。
学完这一章,你能够
- 核对 NLTK、spaCy、jieba 与 HanLP 四大 Python NLP 工具的定位、功能与选型对比,纠正 HanLP 1.x/2.x 接口与 NLTK punkt_tab 变化,并以纯 Python+scikit-learn 实测英文分词/NER、中文 DAG 三模式分词与 TF-IDF 关键词提取。
Python NLP 核心生态与 NLTK/spaCy 英文处理实测
Python 凭借完备的工具链成为自然语言处理开发首选,生态中极具代表性的四大基础库为学术教学向的 NLTK、工业级管道框架 spaCy、轻量中文分词工具 jieba 以及功能全面的中文套件 HanLP。NLTK 由宾夕法尼亚大学主导,涵盖文本分词、词性标注(POS)、命名实体识别(NER)、情感分析、词干提取(Stemming)与词形还原(Lemmatization),优缺点见下表 1;需提示自 NLTK 3.8.2 起分词数据包由旧版 `punkt` 升级为 `punkt_tab`。本站以纯 Python 正则与词典实测复现英文标点切分及词干/词元差异:“Natural language processing is fascinating.” 精确切分为 6 词元 `['Natural', 'language', 'processing', 'is', 'fascinating', '.']`,且 `studies` 词干截断为 `studi` 而词形还原为合法词典原形 `study`,`better` 词形还原为 `good`。
spaCy 面向生产部署设计,提供预训练语言包(如英文 `en_core_web_sm`、中文 `zh_core_web_sm`)、一体化管道处理机制、基于 Cython/神经网络的高效实现以及多语言支持。本站用规则实体识别器在来源标准句 “Apple is looking at buying U.K. startup for $1 billion” 上精确抽取出 `('Apple', 'ORG')`、`('U.K.', 'GPE')` 与 `('$1 billion', 'MONEY')` 三项实体。关于性能差异(来源以文本柱状示意标注 NLTK 约 10,000 词/秒、spaCy 约 100,000 词/秒的数量级参考,实际吞吐取决于硬件与开启的管道组件),本站在 5,000 条英文文档(共 60,000 词元)上离线实测对比 C 底层预编译正则引擎与纯 Python 逐字符循环:两者产出完全一致的 60,000 词元,底层编译引擎吞吐达数百万词/秒级、实测提速逾 2 倍,直观印证底层编译加速的价值。
中文分词与综合工具:jieba 三模式与 HanLP 版本迁移
jieba 是中文分词领域最轻便常用的工具,核心提供三种切分模式:精确模式(追求最合理的无冗余切分)、全模式(扫描句中所有可能成词的子串)与搜索引擎模式(在精确模式基础上对长词二次细切以提升召回),同时支持 `load_userdict()` 加载领域自定义词典,以及 TF-IDF/TextRank 关键词提取、词性标注与多进程并行分词(注:Windows 下多进程接口受操作系统 fork 机制限制)。本站以纯 Python 前缀词典加最大对数概率 DAG 动态规划完整实现三模式与自定义词典实测:对“我爱自然语言处理”,精确模式输出 `['我', '爱', '自然语言', '处理']`,全模式扫出全部 9 个候选含“自然”“语言”“自然语言”,搜索引擎模式将长词“自然语言”补充细分为 `['我', '爱', '自然', '语言', '自然语言', '处理']`;注入自定义词“蓝色天空网”后,“蓝色天空网自然语言教程”的切分立即由拆散的 `['蓝色', '天空', '网', '自然语言', '教程']` 合并为 `['蓝色天空网', '自然语言', '教程']`。
HanLP 定位为一站式生产级中文与多语言(含中、英、日、韩等)NLP 工具集,覆盖多粒度分词、命名实体识别、依存句法分析、文本分类与情感分析。版本迁移提示:来源示例 `from hanlp import HanLP; HanLP.segment(...)` 沿袭了早期 Java 封装版 `pyhanlp`(1.x)调用风格,现代基于深度学习的 HanLP 2.x 统一通过 `hanlp.load(...)` 加载多任务神经模型管道。
工具选型指南、综合流水线实战与官方文档
实际工程选型需兼顾任务复杂度、中文支持与硬件开销(详见下表 2):一般经验上纯分词吞吐倾向 spaCy/jieba 优于 NLTK、深度模型态的 HanLP 内存占用偏高而复杂中文句法语义精度更高(需注意具体排序随所选模型体量及 CPU/GPU 环境变化)。本站在离线环境串联了对应综合中文分析流水线:对“自然语言处理是人工智能的重要分支,近年来发展迅速。”执行 DAG 精确分词(12 项)、规则词性标注(如 `自然语言/n`、`处理/v`、`人工智能/n`、`近年来/t`)、停用词过滤(保留 8 实词)及 scikit-learn `TfidfVectorizer` 关键词抽取,排名前三的关键词为“近年来”(0.4178)、“重要”(0.4178)与“人工智能”(0.3294),且全部停用词零残留。
各工具权威文档入口均收录于下方官方参考区(包括 NLTK、spaCy、jieba 与 HanLP 主页)。整体来看,传统基础工具链负责高效清洗、切词与结构化抽取,未来趋势则持续与 BERT/GPT 预训练大模型、多模态理解、低资源语言建模以及模型可解释性与公平性深度融合。
NLTK 优缺点分析
| 优点 | 缺点 |
|---|---|
| 功能全面,覆盖分词、词性、句法、NER 与语料库等经典教学任务 | 纯 Python 实现为主,大规模文本批处理执行效率较低 |
| 官方文档、教科书与学术案例极为丰富 | 运行前需额外联网下载 punkt_tab/wordnet 等数据包 |
| 算法透明、接口直观,便于拆解 NLP 经典算法教学 | 原生对中文分词与中文句法分析支持有限 |
四大 Python NLP 工具应用场景与特性选型对照
| 工具 | 最佳适用场景 | 中文支持 | 学习曲线 |
|---|---|---|---|
| NLTK | 学术研究、教学与经典英文算法原型 | 有限 | 中等 |
| spaCy | 工业级流水线、高性能多语言生产部署 | 良好(需下载中文模型包) | 平缓 |
| jieba | 轻量快速中文分词、搜索索引切词与自定义词典 | 优秀(精确/全/搜索三模式实测清晰) | 简单 |
| HanLP | 复杂中文分词、NER、依存句法与多任务深度分析 | 优秀(2.x 深度模型覆盖全链路) | 较陡 |
运行英文分词/词干词元/实体规则抽取、中文 DAG 三模式分词、TF-IDF 关键词与编译引擎吞吐对比
"""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()
- 核对英文 6 词元切分与 3 实体抽取、中文精确/全/搜索三模式及自定义词典合并、中文流水线 Top-3 关键词无停用词,以及 C 底层编译正则提速。
所需环境: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。
当前源码 SHA256:1e2e3beba744fd0c0abff199ff03b31ba17ab54902823f64cbf822f48b3d66bd
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境: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。
ZIP SHA256:5e3671a4a7b11e52d4fcef7a07a26797d7b0134ecb29ce7cc58a3dae78408c37
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在搜索引擎建索引场景下,通常更适合使用中文分词的“搜索引擎模式”而非单纯的“精确模式”?
展开参考解答
精确模式会将“自然语言”保留为单一长词,导致用户只搜索“自然”或“语言”时无法命中倒排索引;搜索引擎模式对长词再切分并同步保留原长词(如产出“自然”“语言”“自然语言”),显著提高检索召回率。