目录
下载相对应的模块:
import nltk
nltk.download()
分词
导入包:
from nltk.tokenize import word_tokenize
分词操作:
# 分词操作
list1 = word_tokenize(str)#返回一个列表类型
print(list1)
#转化为Text对象,方便后续操作
t = Text(list1)
print(t.count('my'))#统计单词出现次数
print(t.index('is'))#返回索引
# t.plot(3)#画图,统计前三个出现次数最多的词
停用词过滤
导入包:
from nltk.corpus import stopwords # 语料库中的停用词表
停用词过滤操作:
print(stopwords.fileids())# 查看停用词表支持的语言类型
print(stopwords.raw('chinese'))# 查看某一语言的停用词表
testWord = [l.lower() for l in list1]
testWordSet = set(testWord)# 去重
print(testWordSet.intersection(set(stopwords.words('english'))))# 获得与english停用词的交集
filtered = [w for w in testWordSet if (w not in stopwords.words('english'))]# 过滤停用词
print(filtered)
词性标注
导入包:
from nltk import pos_tag# 词性标注所依赖的库
词性标注操作:
#词性标注(需要先分词)
tags = pos_tag(list1)
print(tags)
命名实体识别
导入包:
from nltk import ne_chunk# 命名实体识别所依赖库
实体识别操作:
#命名实体识别(需要先分词和词性标注)
identities = ne_chunk(tags)
print(identities)