NLTK 与 NLP 基础:语料库、语法树与分类器

知识库
知识库文档
/tech-stacks/nltk/tutorial/NLTK 与 NLP 基础:语料库、语法树与分类器.md

文档

NLTK 入门教程:语料库、语法树与分类器

1. NLTK 的定位

NLTK 不是工业级工具(那是 spaCy 的事),而是NLP 教学的瑞士军刀。它的价值在于让你理解"分词到底在干什么"、"语法树怎么构建"——而不是黑盒调用。

「如果你只想知道结果,用 spaCy。如果你想理解为什么,用 NLTK。」

2. 内置语料库

from nltk.corpus import brown, gutenberg, reuters, inaugural

# Brown 语料库:100 万词的标注语料(新闻、小说、科技等 15 类)
print(brown.categories())
# ['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', ...]

# Gutenberg:经典文学
print(gutenberg.fileids())
# ['austen-emma.txt', 'shakespeare-hamlet.txt', ...]

# 查看特定文本
emma = nltk.Text(gutenberg.words("austen-emma.txt"))
emma.concordance("love")  # 查看 "love" 的上下文

3. 条件频率分布

from nltk.probability import ConditionalFreqDist

cfd = ConditionalFreqDist(
    (genre, word)
    for genre in brown.categories()
    for word in brown.words(categories=genre)
)

# 各体裁中最常用的情态动词
genres = ["news", "romance", "science_fiction"]
modals = ["can", "could", "may", "might", "must", "will"]
cfd.tabulate(conditions=genres, samples=modals)

4. 上下文无关文法 (CFG)

grammar = nltk.CFG.fromstring("""
    S -> NP VP
    NP -> Det N | Det N PP | 'I'
    VP -> V NP | VP PP
    PP -> P NP
    Det -> 'the' | 'a'
    N -> 'dog' | 'cat' | 'park'
    V -> 'saw' | 'chased'
    P -> 'in' | 'with'
""")

parser = nltk.ChartParser(grammar)
sentence = "the dog saw a cat in the park".split()
for tree in parser.parse(sentence):
    tree.pretty_print()

CFG 帮助你理解"句法歧义"——同一句话可能有多种解析树。

5. 朴素贝叶斯文本分类

from nltk.classify import NaiveBayesClassifier

# 构造特征
def extract_features(words):
    return {word: True for word in words}

# 训练数据
pos_sents = [("I love this movie".split(), "positive"),
             ("Great film amazing acting".split(), "positive")]
neg_sents = [("Terrible movie waste of time".split(), "negative"),
             ("Boring and slow".split(), "negative")]

train_data = [(extract_features(words), label) for words, label in pos_sents + neg_sents]
classifier = NaiveBayesClassifier.train(train_data)

# 预测
test = extract_features("Great acting".split())
print(classifier.classify(test))  # positive
print(classifier.show_most_informative_features(5))

6. NLTK vs spaCy:教科书 vs 工业

任务 NLTK spaCy
教学学习 ⭐⭐⭐
分词 多算法可选 单一最优
NER 基于规则 基于统计(更准)
速度 慢(Python 实现) 极快(Cython)
句法树 ⭐⭐⭐(CFG) ⭐(仅依存)
语料库 ⭐⭐⭐ 丰富 ⭐ 无内置

7. 推荐学习路径

NLTK 入门(理解原理)
  → spaCy 实战(高效生产)
    → HuggingFace Transformers(SOTA 精度)
      → LangChain(LLM 应用)

思考题

  1. NLTK 的 Porter Stemmer 和 WordNet Lemmatizer 各有什么优缺点?
  2. 为什么工业界选 spaCy 而不是 NLTK?NLTK 有什么不可替代的地方?
  3. 用 NLTK 的 CFG 解析中文句子会遇到什么挑战?

信息

路径
/tech-stacks/nltk/tutorial/NLTK 与 NLP 基础:语料库、语法树与分类器.md
更新时间
2026/5/31