Python的NLTK(Natural Language Toolkit)库为语言处理提供了强大的工具和资源。本学习笔记将通过一个实际的例子,介绍如何使用NLTK进行基本的文本分析任务。
# 导入NLTK库的必要组件
import nltk
from nltk.tokenize import word_tokenize # 分词
from nltk.corpus import stopwords # 获取停用词列表
from nltk import pos_tag # 进行词性标注
from nltk.chunk import RegexpChunkParser # 创建正则表达式分块解析器
from nltk import ne_chunk # 命名实体识别
# 分析的文本字符串
mystring = 'Its informal conversational style would make interaction comfortable, and yet the machine would remain slightly unpredictable and therefore interesting.'
# 对文本进行分词处理
tokens = word_tokenize(mystring)
# 将分词结果转换为小写,以便统一处理
tokens = [word.lower() for word in tokens]
# 将分词结果转换为集合,以去除重复的词汇
tokens_set = set(tokens)
# 过滤掉分词结果中的停用词
filtered_words = [w for w in tokens_set if(w not in stopwords.words('english'))]
# 对过滤后的词汇进行词性标注
tags = pos_tag(filtered_words)
此时tags为下面的列表:
[('remain', 'NN'),
('.', '.'),
('slightly', 'RB'),
('informal', 'JJ'),
('yet', 'RB'),
('would', 'MD'),
('interaction', 'VB'),
('conversational', 'JJ'),
('style', 'NN'),
('machine', 'NN'),
('interesting', 'VBG'),
('unpredictable', 'JJ'),
(',', ','),
('therefore', 'RB'),
('make', 'VBP'),
('comfortable', 'JJ')]
各个词性的含义参照下表:
'''
NN: 名词 (Noun)
NNS: 复数名词 (Noun, plural)
NNP: 专有名词 (Proper noun, singular)
NNPS: 复数专有名词 (Proper noun, plural)
PRP: 人称代词 (Personal pronoun)
PRP$: 物主代词 (Possessive pronoun)
RB: 副词 (Adverb)
RBR: 比较级副词 (Adverb, comparative)
RBS: 最高级副词 (Adverb, superlative)
VB: 动词原形 (Verb, base form)
VBD: 动词过去式 (Verb, past tense)
VBG: 现在分词 (Verb, gerund or present participle)
VBN: 过去分词 (Verb, past participle)
VBP: 动词非第三人称单数现在时 (Verb, non-3rd person singular present)
VBZ: 动词第三人称单数现在时 (Verb, 3rd person singular present)
JJ: 形容词 (Adjective)
JJR: 比较级形容词 (Adjective, comparative)
JJS: 最高级形容词 (Adjective, superlative)
DT: 限定词 (Determiner)
CC: 连词 (Coordinating conjunction)
IN: 介词或从属连词 (Preposition or subordinating conjunction)
MD: 情态动词 (Modal)
CD: 基数 (Cardinal number)
EX: 存在量词 (Existential there)
FW: 外来词 (Foreign word)
POS: 所有格结束词 (Possessive ending)
RP: 小品词 (Particle)
SYM: 符号 (Symbol)
TO: "to" 作为介词或不定式标记 (to)
WDT: wh-限定词 (Wh-determiner)
WP: wh-代词 (Wh-pronoun)
WP$: wh-物主代词 (Possessive wh-pronoun)
WRB: wh-副词 (Wh-adverb)
'''
# 定义句子结构的语法规则
grammar = "NP: {<DT>?<JJ>*<NN>}"
# 创建一个句子对象,用于解析
sentence = nltk.sent_tokenize(mystring)[0]
# 使用上面定义的语法规则,创建一个正则表达式分块解析器
cp = nltk.RegexpParser(grammar)
# 解析句子,生成一个树结构
result = cp.parse(tags)
# 打印解析结果
print(result)
# 绘制树结构
result.draw()
绘制出来的树:
# 进行命名实体识别的另一个示例
sentence = 'Ada went to Wuhan University today'
# 打印命名实体识别的结果
print(ne_chunk(pos_tag(word_tokenize(sentence))))
结果:
(S
(PERSON Ada/NNP)
went/VBD
to/TO
(PERSON Wuhan/NNP University/NNP)
today/NN)
spaCy库也有类似的功能,且识别更准确,可参考另一篇文章:自然语言处理:Python的spaCy库及文章人名统计
NLTK作为一个功能强大的语言处理工具,为我们提供了探索语言的丰富资源和方法。随着技术的深入,我们期待解锁更多自然语言处理的秘密,开启语言和计算机之间更深层次的交流。