NLTK使用方法总结
目录
1. NLTK安装与功能描述
2. NLTK词频统计(Frequency)
3. NLTK去除停用词(stopwords)
4. NLTK分句和分词(tokenize)
5. NLTK词干提取 (Stemming)
6. NLTK词形还原(Lemmatization)
7. NLTK词性标注(POS Tag)
8. NLTK中的wordnet
NLTK(natural language toolkit)是一套基于python的自然语言处理工具集。
1. NLTK安装与功能描述
(1)NLTK安装
首先,打开终端安装nltk
pip install nltk
打开Python终端并输入以下内容来安装 NLTK 包
import nltk
nltk.download()
(2)语言处理任务与相应NLTK模块以及功能描述
(3)NLTK自带的语料库(corpus)
在nltk.corpus包下,提供了几类标注好的语料库。见下表
语料库 | 说明 |
gutenberg | 一个有若干万部的小说语料库,多是古典作品 |
webtext | 收集的网络广告等内容 |
nps_chat | 有上万条聊天消息语料库,即时聊天消息为主 |
brown | 一个百万词级的英语语料库,按文体进行分类 |
reuters | 路透社语料库,上万篇新闻方档,约有1百万字,分90个主题,并分为训练集和测试集两组 |
inaugural | 演讲语料库,几十个文本,都是总统演说 |
from nltk.corpus import brown
print(brown.categories()) #输出brown语料库的类别
print(len(brown.sents())) #输出brown语料库的句子数量
print(len(brown.words())) #输出brown语料库的词数量'''
结果为:
['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies',
'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance',
'science_fiction']
57340
1161192
'''
2. NLTK词频统计(Frequency)
NLTK 中的FreqDist( ) 类主要记录了每个词出现的次数,根据统计数据生成表格或绘图。其结构简单,用一个有序词典进行实现。
方法 | 作用 |
B() | 返回词典的长度 |
plot(title,cumulative=False) | 绘制频率分布图,若cumu为True,则是累积频率分布图 |
tabulate() | 生成频率分布的表格形式 |
most_common() | 返回出现次数最频繁的词与频度 |
hapaxes() | 返回只出现过一次的词 |
词频统计功能实现如下:
import nltk
tokens=[ 'my','dog','has','flea','problems','help','please','maybe','not','take','him','to','dog','park','stupid','my','dalmation','is','so','cute','I','love','him' ]
#统计词频
freq = nltk.FreqDist(tokens)#输出词和相应的频率
for key,val in freq.items():print (str(key) + ':' + str(val))#可以把最常用的5个单词拿出来
standard_freq=freq.most_common(5)
print(standard_freq)#绘图函数为这些词频绘制一个图形
freq.plot(20, cumulative=False)
3. NLTK去除停用词(stopwords)
from nltk.corpus import stopwords
tokens=[ 'my','dog','has','flea','problems','help','please','maybe','not','take','him','to','dog','park','stupid','my','dalmation','is','so','cute','I','love','him' ]clean_tokens=tokens[:]
stwords=stopwords.words('english')
for token in tokens:if token in stwords:clean_tokens.remove(token)print(clean_tokens)
4. NLTK分句和分词(tokenize)
(1)nltk分句
from nltk.tokenize import sent_tokenize
mytext = "Hello Adam, how are you? I hope everything is going well. Today is a good day, see you dude."
print(sent_tokenize(mytext))
结果如下:
['Hello Adam, how are you?', 'I hope everything is going well.', 'Today is a good day, see you dude.']
(2) nltk分词
from nltk.tokenize import word_tokenize
mytext = "Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude."
print(word_tokenize(mytext))
结果如下:
['Hello', 'Mr.', 'Adam', ',', 'how', 'are', 'you', '?', 'I', 'hope', 'everything', 'is', 'going', 'well', '.', 'Today', 'is', 'a', 'good', 'day', ',', 'see', 'you', 'dude', '.']
(3) nltk标记非英语语言文本
from nltk.tokenize import sent_tokenize
mytext = "Bonjour M. Adam, comment allez-vous? J'espère que tout va bien. Aujourd'hui est un bon jour."
print(sent_tokenize(mytext,"french"))
结果如下:
['Bonjour M. Adam, comment allez-vous?', "J'espère que tout va bien.", "Aujourd'hui est un bon jour."]
5. NLTK词干提取 (Stemming)
单词词干提取就是从单词中去除词缀并返回词根。(比方说 working 的词干是 work。)搜索引擎在索引页面的时候使用这种技术,所以很多人通过同一个单词的不同形式进行搜索,返回的都是相同的,有关这个词干的页面。
词干提取的算法有很多,但最常用的算法是 Porter 提取算法。NLTK 有一个 PorterStemmer 类,使用的就是 Porter 提取算法。
(1) PorterStemmer
from nltk.stem import PorterStemmer
porter_stemmer = PorterStemmer()
print(porter_stemmer.stem('working'))
#结果为:work
(2)LancasterStemmer
from nltk.stem import LancasterStemmer
lancaster_stemmer = LancasterStemmer()
print(lancaster_stemmer.stem('working'))
#结果为:work
(3)SnowballStemmer 提取非英语单词词干
SnowballStemmer 类,除了英语外,还可以适用于其他 13 种语言。支持的语言如下:
from nltk.stem import SnowballStemmer
print(SnowballStemmer.languages)
#结果为:
('danish', 'dutch', 'english', 'finnish', 'french', 'german', 'hungarian', 'italian', 'norwegian', 'porter', 'portuguese', 'romanian', 'russian', 'spanish', 'swedish')
使用 SnowballStemmer 类的 stem() 函数来提取非英语单词
from nltk.stem import SnowballStemmer
french_stemmer = SnowballStemmer('french')
print(french_stemmer.stem("French word"))
#结果为:french word
6. NLTK词形还原(Lemmatization)
(1)词形还原与词干提取类似, 但不同之处在于词干提取经常可能创造出不存在的词汇,词形还原的结果是一个真正的词汇。
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize('increases'))#结果为:increase
(2) 结果可能是同义词或具有相同含义的不同词语。有时,如果你试图还原一个词,比如 playing,还原的结果还是 playing。这是因为默认还原的结果是名词,如果你想得到动词,可以通过以下的方式指定。
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize('playing', pos="v"))#结果为:play
(3)实际上,这是一个非常好的文本压缩水平。最终压缩到原文本的 50% 到 60% 左右。结果可能是动词,名词,形容词或副词:
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize('playing', pos="v"))
print(lemmatizer.lemmatize('playing', pos="n"))
print(lemmatizer.lemmatize('playing', pos="a"))
print(lemmatizer.lemmatize('playing', pos="r"))
'''
结果为:
play
playing
playing
playing
'''
7. NLTK词性标注(POS Tag)
(1)词性标注是把一个句子中的单词标注为名词,形容词,动词等。
import nltk
text=nltk.word_tokenize('what does the fox say')
print(text)
print(nltk.pos_tag(text))'''
结果为:
['what', 'does', 'the', 'fox', 'say']输出是元组列表,元组中的第一个元素是单词,第二个元素是词性标签
[('what', 'WDT'), ('does', 'VBZ'), ('the', 'DT'), ('fox', 'NNS'), ('say', 'VBP')]
'''
(2)简化的词性标记集列表(Part of Speech)
标记(Tag) | 含义(Meaning) | 例子(Examples) |
ADJ | 形容词(adjective) | new,good,high,special,big |
ADV | 副词(adverb) | really,,already,still,early,now |
CNJ | 连词(conjunction) | and,or,but,if,while |
DET | 限定词(determiner) | the,a,some,most,every |
EX | 存在量词(existential) | there,there's |
FW | 外来词(foreign word) | dolce,ersatz,esprit,quo,maitre |
MOD | 情态动词(modal verb) | will,can,would,may,must |
N | 名词(noun) | year,home,costs,time |
NP | 专有名词(proper noun) | Alison,Africa,April,Washington |
NUM | 数词(number) | twenty-four,fourth,1991,14:24 |
PRO | 代词(pronoun) | he,their,her,its,my,I,us |
P | 介词(preposition) | on,of,at,with,by,into,under |
TO | 词 to(the word to) | to |
UH | 感叹词(interjection) | ah,bang,ha,whee,hmpf,oops |
V | 动词(verb) | is,has,get,do,make,see,run |
VD | 过去式(past tense) | said,took,told,made,asked |
VG | 现在分词(present participle) | making,going,playing,working |
VN | 过去分词(past participle) | given,taken,begun,sung |
WH | wh限定词(wh determiner) | who,which,when,what,where |
NLTK词性标注编码含义
8. NLTK中的wordnet
wordnet 是为自然语言处理构建的数据库。它包括部分词语的一个同义词组和一个简短的定义。
(1)通过 wordnet可以得到给定词的定义和例句
from nltk.corpus import wordnet
syn = wordnet.synsets("pain") #获取“pain”的同义词集
print(syn[0].definition())
print(syn[0].examples())'''
结果为:
a symptom of some physical hurt or disorder
['the patient developed severe pain and distension']
'''
(2)使用 wordnet来获得同义词
from nltk.corpus import wordnet
synonyms = []
for syn in wordnet.synsets('Computer'):for lemma in syn.lemmas():synonyms.append(lemma.name())
print(synonyms)'''
结果为:
['computer', 'computing_machine', 'computing_device', 'data_processor', 'electronic_computer', 'information_processing_system', 'calculator', 'reckoner', 'figurer', 'estimator', 'computer']
'''
(3)使用wordnet来获取反义词
from nltk.corpus import wordnet
antonyms = []
for syn in wordnet.synsets("small"):for l in syn.lemmas():if l.antonyms(): #判断是否是正确的反义词antonyms.append(l.antonyms()[0].name())
print(antonyms)'''
结果为:
['large', 'big', 'big']
'''
交流学习资料共享欢迎入QQ群:955817470
NLTK使用方法总结相关推荐
- win10 64位下Python中NLTK,pip,numpy等安装方法
win64下Python中NLTK的安装方法 Python已经更新至3.6版本,但是2.7.3的版本也足以使用.但是win64版本之下却没有Python中NLTK的安装包,网络之上的NLTK安装方法也 ...
- NLTK使用英文词性还原
安装NLTK的方法请参考:https://blog.csdn.net/weixin_35757704/article/details/115629297 词性还原 Lemmatization from ...
- Python 数据科学入门教程:NLTK
自然语言处理教程 原文:Natural Language Process 译者:飞龙 协议:CC BY-NC-SA 4.0 一.使用 NLTK 分析单词和句子 欢迎阅读自然语言处理系列教程,使用 Py ...
- python 英语分词_自然语言处理 | NLTK英文分词尝试
NLTK是一个高效的Python构建的平台,用来处理自然语言数据,它提供了易于使用的接口,通过这些接口可以访问超过50个语料库和词汇资源(如WordNet),还有一套用于分类.标记化.词干标记.解析和 ...
- NLP常见语言模型及数据增强方法总结
文章目录 一.NLP常见语言模型 1.词的离散表示 1.One-hot编码(独热编码) 2.Bag of Words(BOW,词袋模型) 3.N-gram语言模型 2.词的分布式表示 1.共现矩阵(C ...
- NLP数据增强方法总结及实现
目录 1.数据增强 2.简单数据增强(Easy Data Augmentation,EDA) (1)EDA方法 (2)EDA工具使用方法 (3)EDA相关工具 3.回译 4.基于上下文的数据增强方法 ...
- Anaconda3安装jieba库和NLTK库
当我们进行文本处理时,常常需要对文本进行分词处理,但是中文与英文的处理方式确实不一样的:英文主要利用空格进行单词或者句子划分,所以使用的是NLTK分词方法:而中文比英文复杂,需要进行预处理等操作,使 ...
- 不平衡数据集处理方法
目录 1.不平衡(均衡)数据集 (1)不平衡数据集定义 (2)不平衡数据集举例 (3)不平衡数据集实例 (4)不平衡数据集导致的问题 (5)不平衡数据集的主要处理方法 2.不平衡(均衡)数据集常用的处 ...
- 使用Python+NLTK实现英文单词词频统计
使用Python+NLTK实现英文单词词频统计 使用PythonNLTK实现英文单词词频统计 应用场景 Fork Me 参考运行环境 流程步骤图 详细步骤 读取文件 过滤特殊符号以及还原常见缩写单词 ...
- python制作聊天机器人原理_用 Python 来做一个聊天机器人吧!(一)
在我的一个回答里,我提到了用 Python 搭建聊天机器人.从今天开始,我就带着大家从0开始搭建一个聊天机器人. (顺便说一句,我喜欢把链接像上面这样加在文字里,如果找不到文中所说的资源,可以看看周围 ...
最新文章
- 拿下两个世界第一,阿里人机对话模型成人工智能国际通用标准
- 相同的字符串哈希值一样吗_关于哈希,来看这里!
- webpack 中的加载器简介||webpack 中加载器的基本使用——1. 打包处理 css 文件 2. 打包处理 less 文件 3.打包处理 scss 文件
- php 截取字符串的方法,php截取字符串的方法介绍
- 初步认识Volatile-MESI优化带来的可见性问题
- go errgroup 递归搜索目录中的Go文件
- (二)linux内核镜像制作
- Android实例-屏幕操持常亮(XE8+小米2)
- word模板生成利器poi-tl
- 【杂项】vmware fusion 流畅度设置
- 三菱5uplc伺服电机指令_【工控无忧原创】三菱FX3U PLC如何控制松下伺服
- 批量处理word文档向下箭头
- php需要session么,php – 为什么需要session_ destroy()?
- require.js的简单使用
- 数字摄影测量之特征点提取算法
- [Java并发-14] Future: 优雅的使用多线程
- Python做数据处理(二):贷款风险预测
- Luogu P2448 无尽的生命
- app2sd 与 A2SD+
- 文件函数python_Python 基础之文件 函数