自然语言处理工具包
NLTK
NLTK,全称Natural Language Toolkit,自然语言处理工具包,是NLP研究领域常用的一个Python库
nltk需要下载语料库,使用nltk.download()下载
Tips:如果下载失败可以访问下载器的url或者在网上找一份手动下载,然后拖到对应文件夹即可
分词
nltk.sent_tokenize(text) #对文本按照句子进行分割
nltk.word_tokenize(sent) #对句子进行分词
import nltk
text = 'PathonTip.com is a very good website. We can learn a lot from it.'
#将文本拆分成句子列表
sens = nltk.sent_tokenize(text)
print(sens)
#将句子进行分词,nltk的分词是句子级的,因此要先分句,再逐句分词,否则效果会很差.
words = []
for sent in sens:
words.append(nltk.word_tokenize(sent))
print(words)
['PathonTip.com is a very good website.', 'We can learn a lot from it.']
[['PathonTip.com', 'is', 'a', 'very', 'good', 'website', '.'], ['We', 'can', 'learn', 'a', 'lot', 'from', 'it', '.']]
词性标注
nltk的词性表示
CC 并列连词 NNS 名词复数 UH 感叹词
CD 基数词 NNP 专有名词 VB 动词原型
DT 限定符 NNP 专有名词复数 VBD 动词过去式
EX 存在词 PDT 前置限定词 VBG 动名词或现在分词
FW 外来词 POS 所有格结尾 VBN 动词过去分词
IN 介词或从属连词 PRP 人称代词 VBP 非第三人称单数的现在时
JJ 形容词 PRP$ 所有格代词 VBZ 第三人称单数的现在时
JJR 比较级的形容词 RB 副词 WDT 以wh开头的限定词
JJS 最高级的形容词 RBR 副词比较级 WP 以wh开头的代词
LS 列表项标记 RBS 副词最高级 WP$ 以wh开头的所有格代词
MD 情态动词 RP 小品词 WRB 以wh开头的副词
NN 名词单数 SYM 符号 TO 就是to
nltk.pos_tag(tokens)#tokens是句子分词后的结果,同样是句子级的标注
tags = []
#词性标注要利用上一步分词的结果
for tokens in words:
tags.append(nltk.pos_tag(tokens))
print(tags)
命名实体识别(NER)
nltk.ne_chunk(tags)#tags是句子词性标注后的结果,同样是句子级
import nltk
nltk.download('maxent_ne_chunker')
text = 'Xi is the chairman of China in the year 2013.'
#分词
tokens = nltk.word_tokenize(text)
#词性标注
tags = nltk.pos_tag(tokens)
# print(tags)
#NER需要利用词性标注的结果
ners = nltk.ne_chunk(tags)
print(ners)
[('Xi', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('chairman', 'NN'), ('of', 'IN'), ('China', 'NNP'), ('in', 'IN'), ('the', 'DT'), ('year', 'NN'), ('2013', 'CD'), ('.', '.')]
Spacy
Spacy 是由 cython 编写,效率比nltk快得多。
与nltk用法相似
import spacy
#加载默认的模块
nlp = spacy.load(“en”)
#词性标注
doc = nlp("He went to play basketball")
# 遍历token
for token in doc:
# Print the token and its part-of-speech tag
print(token.text, "-->", token.pos_)
#依存分析
#每个句子都有一个语法结构,通过依存句法分析,我们可以提取出这个结构。它也可以看作是一个有向图,其中节点对应于句子中的单词,节点之间的边是单词之间的对应依赖关系。
for token in doc:
print(token.text, "-->", token.dep_)
#命名实体识别
doc = nlp("Indians spent over $71 billion on clothes in 2018")
for ent in doc.ents:
print(ent.text, ent.label_)
#句子解析可视化
from spacy import displacy
displacy.render(doc, style="dep")
两个自然语言处理工具包还有许多功能,此处仅列举部分,更多可以查看https://spacy.io/,https://yiyibooks.cn/yiyi/nltk_python/index.html,https://blog.wikty.com/post/nlp/nltk/等