NLTK(Natural language toolkit)使用方法总结

版权声明: https://blog.csdn.net/asialee_bird/article/details/85936784

NLTK(natural language toolkit)是一套基于python的自然语言处理工具集。

目录

1. NLTK安装与功能描述

2. NLTK词频统计(Frequency)

3. NLTK去除停用词(stopwords)

 4. NLTK分句和分词(tokenize)

5. NLTK词干提取 (Stemming)

6. NLTK词形还原(Lemmatization)  

7. NLTK词性标注(POS Tag)

8. NLTK中的wordnet

 

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']
'''

猜你喜欢

转载自blog.csdn.net/asialee_bird/article/details/85936784
今日推荐