NLTK模块使用详解

[TOC]

NLTK模块使用详解

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

一、NLTK的安装+简介

(1)、NLTK安装

win+r打开并输入cmd回车打开终端

在终端中输入以下代码进行安装

pip3 install nltk

(2)、NLTK模块功能

(3)、NLTK中的语料库

在nltk.corpus包中,提供了几种标注好的语料库可以直接加载使用。如下:

(4)、加载语料库

这里以brown语料库进行讲解,其他语料库的使用方式大致相同

查看语料库的加载路径。当我们加载时,我们的系统会帮我们把brown语料库下载到data的指定路径

from nltk.corpus import brown

import nltk

print(nltk.data.path) # 查看语料库存储路径

"""

E:\Anaconda\envs\NLP_py3.11\python.exe D:\PYTHON_PROJECT\NLP\1.py

['C:\\Users\\34435/nltk_data', 'E:\\Anaconda\\envs\\NLP_py3.11\\nltk_data', 'E:\\Anaconda\\envs\\NLP_py3.11\\share\\nltk_data', 'E:\\Anaconda\\envs\\NLP_py3.11\\lib\\nltk_data', 'C:\\Users\\34435\\AppData\\Roaming\\nltk_data', 'C:\\nltk_data', 'D:\\nltk_data', 'E:\\nltk_data']

进程已结束,退出代码为 0

"""

指定数据加载的目录。我门也可以在加载时指定数据加载的目录

方法一:使用nltk.data.path,在下载数据前,我们可以设置NLTK的下载目录

from nltk.corpus import brown

import nltk

nltk.data.path.append('D:\\PYTHON_PROJECT\\NLP\\data')

nltk.download('brown')

"""

E:\Anaconda\envs\NLP_py3.11\python.exe D:\PYTHON_PROJECT\NLP\1.py

[nltk_data] Downloading package brown to

[nltk_data] D:\PYTHON_PROJECT\NLP\data\nltk_data...

[nltk_data] Unzipping corpora\brown.zip.

进程已结束,退出代码为 0

"""

方法二:使用NLTK Downloader,如果希望在下载时选择目录,可以使用 NLTK 的下载器手动指定。运行以下命令:

import nltk

nltk.download()

"""

E:\Anaconda\envs\NLP_py3.11\python.exe D:\PYTHON_PROJECT\NLP\1.py

showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml

"""

​ 这将打开上图所示的图形界面的下载器,您可以在其中选择下载目录。在下载器的菜单中,选择 "File" -> "Change NLTK Data Directory" 来更改数据目录,然后下载所需的资源。

方法三:直接在环境变量中进行设置。通过设置环境变量来指定默认的 NLTK 数据目录,具体操作视操作系统而定

windows系统如下操作:在环境变量中添加NLTK_DATA,并将其值设置为指定的下载路径

​ macos和linux系统:在终端中运行:

export NLTK_DATA='/your/desired/path/nltk_data'

方法四:直接传递参数下载。可以直接在调用 nltk.download() 时传递参数来指定下载路径(需要 Python 3.8 及以上版本):

import nltk

nltk.download('brown', download_dir='D:\\PYTHON_PROJECT\\NLP\\data')

"""

E:\Anaconda\envs\NLP_py3.11\python.exe D:\PYTHON_PROJECT\NLP\1.py

[nltk_data] Downloading package brown to D:\PYTHON_PROJECT\NLP\data...

[nltk_data] Unzipping corpora\brown.zip.

进程已结束,退出代码为 0

"""

(5)、基础语法

from nltk.corpus import brown

import nltk

print(brown.categories()) # 查看brown语料库的类别

print(len(brown.sents())) # 查看brown语料库的句子数量

print(len(brown.words())) # 查看brown语料库的词数量

二、NLTK词频统计(Frequency)

NLTK 中的FreqDist( ) 类主要记录了每个词出现的次数,根据统计数据生成表格或绘图。其结构简单,用一个有序词典进行实现。

方法

作用

B()

返回词典的长度

plot(title,cumulative=False)

绘制频率分布图,若cumu为True,则是累积频率分布图

tabulate()

生成频率分布的表格形式

most_common()

返回出现次数最频繁的词与频度

hapaxes()

返回只出现过一次的词

代码示例:

from nltk.corpus import brown

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))

standard_freq=freq.most_common(5)

freq.plot(20, cumulative=False)

"""

E:\Anaconda\envs\NLP_py3.11\python.exe D:\PYTHON_PROJECT\NLP\1.py

my:2

dog:2

has:1

flea:1

problems:1

help:1

please:1

maybe:1

not:1

take:1

him:2

to:1

park:1

stupid:1

dalmation:1

is:1

so:1

cute:1

I:1

love:1

进程已结束,退出代码为 0

"""

三、NLTK去除停用词(stopwords)

​ 我们可以使用remove方法去除掉停用的词;示例代码:

from nltk.corpus import brown, stopwords

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

stwords=stopwords.words('english')

tokens.remove(stwords)

print(tokens)

四、NLTK分词和分句(tokenize)

(1)、nltk分句

​ 使用sent_tokensize()方法可以很简单进行分句。示例代码:

from nltk import sent_tokenize

from nltk.corpus import brown, stopwords

import nltk

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分词

​ 使用word_tokenize()方法可以实现分词效果。示例代码:

from nltk import sent_tokenize, word_tokenize

from nltk.corpus import brown, stopwords

import nltk

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标记非英语语言文本

​ 使用sent_tokenize()方法标记非英文语言文本。示例代码:

from nltk import sent_tokenize, word_tokenize

from nltk.corpus import brown, stopwords

import nltk

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."]

"""

五、NLTK词干提取(Stemming)

​ 单词词干提取就是从单词中去除词缀并返回词根。(比方说 working 的词干是 work。)搜索引擎在索引页面的时候使用这种技术,所以很多人通过同一个单词的不同形式进行搜索,返回的都是相同的,有关这个词干的页面。​ 词干提取的算法有很多,但最常用的算法是 Porter 提取算法。NLTK 有一个 PorterStemmer 类,使用的就是 Porter 提取算法。

(1) PorterStemmer方法

from nltk.stem import PorterStemmer

porter_stemmer = PorterStemmer()

print(porter_stemmer.stem('working'))

(2)LancasterStemmer方法

from nltk.stem import LancasterStemmer

lancaster_stemmer = LancasterStemmer()

print(lancaster_stemmer.stem('working'))

(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"))

六. NLTK词形还原(Lemmatization)

(1)词形还原与词干提取类似, 但不同之处在于词干提取经常可能创造出不存在的词汇,词形还原的结果是一个真正的词汇。

from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize('increases'))

(2) 结果可能是同义词或具有相同含义的不同词语。有时,如果你试图还原一个词,比如 playing,还原的结果还是 playing。这是因为默认还原的结果是名词,如果你想得到动词,可以通过以下的方式指定。

from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize('playing', pos="v"))

(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"))

七、NLTK词性标注(POS Tag)

(1)词性标注是把一个句子中的单词标注为名词,形容词,动词等。

text=nltk.word_tokenize('what does the fox say')

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

含义(Meaning)

new,good,high,special,big

ADV

形容词(adjective)

really,,already,still,early,now

CNJ

副词(adverb)

and,or,but,if,while

DET

连词(conjunction)

the,a,some,most,every

EX

限定词(determiner)

there,there's

FW

存在量词(existential)

dolce,ersatz,esprit,quo,maitre

MOD

外来词(foreign word)

will,can,would,may,must

N

情态动词(modal verb)

year,home,costs,time

NP

名词(noun)

Alison,Africa,April,Washington

NUM

专有名词(proper noun)

twenty-four,fourth,1991,14:24

PRO

数词(number)

he,their,her,its,my,I,us

P

代词(pronoun)

on,of,at,with,by,into,under

TO

介词(preposition)

to

UH

词 to(the word to)

ah,bang,ha,whee,hmpf,oops

V

感叹词(interjection)

is,has,get,do,make,see,run

VD

动词(verb)

said,took,told,made,asked

VG

过去式(past tense)

making,going,playing,working

VN

现在分词(present participle)

given,taken,begun,sung

WH

wh限定词(wh determiner)

who,which,when,what,where

编码含义

九、NLTK中的wordnet

wordnet 是为自然语言处理构建的数据库。它包括部分词语的一个同义词组和一个简短的定义。

(1)通过 wordnet可以得到给定词的定义和例句

from nltk.corpus import wordnet

syn = wordnet.synsets("pain") #获取“pain”的同义词集

print(syn[0].definition())

a symptom of some physical hurt or disorder

['the patient developed severe pain and distension']

(2)使用 wordnet来获得同义词

from nltk.corpus import wordnet

for syn in wordnet.synsets('Computer'):

for lemma in syn.lemmas():

synonyms.append(lemma.name())

['computer', 'computing_machine', 'computing_device', 'data_processor', 'electronic_computer', 'information_processing_system', 'calculator', 'reckoner', 'figurer', 'estimator', 'computer']

(3)使用wordnet来获取反义词

from nltk.corpus import wordnet

for syn in wordnet.synsets("small"):

for l in syn.lemmas():

if l.antonyms(): #判断是否是正确的反义词

antonyms.append(l.antonyms()[0].name())

2025-10-02 07:52:49
办一张电信卡到底要多少钱?5元保号到200元账单,90%的人算不清这笔账!
《星际穿越》是好的投资吗?