一.基本情况
1.介绍:
这是Python上著名的自然语言处理库,自带语料库/词性分类库,自带分类/分词等功能,还拥有强大的社区支持和大量简单版wrapper,如Textblob
2.准备
(1)安装该库:
pip install nltk
#推荐也安装上Numpy:
pip install numpy
(2)安装该库中包含的包:
>>> nltk.download(["<package>"])、
#参数说明:
package:指定要下载的包;为str
如果不指定参数,执行后跳出如下的窗口,然后可以选择要下载的内容:
注意:NLTK Downloader的一键下载很多时候会出现卡顿/下载失败/"out of date"标记,这时,只需要暂停现有下载,切换到
All Packages页面,然后双击相应的包,即可完成下载
二.功能
1.语料库
(1)语料库集合:
nltk.corpus
该模块中包含多个语料库,可通过 一.2.(2) 中的图中的Corpora栏查看
(2)查看语料库的相关信息:
<cor>.categories():查看该语料库包含的条目
#即查看该库中的语料被分成哪些类别
#返回1个list,其中元素是条目名(为str)
#参数说明:
cor:指定语料库
#实例:
>>> import nltk
>>> nltk.corpus.brown.categories()
['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance', 'science_fiction']
#########################################################################################
<cor>.sents():返回该语料库包含的语句
#返回1个列表,其中的元素也是列表且这些列表中的元素是1个语句中的所有单词
<cor>.words():返回该语料库包含的单词
#返回1个列表
#参数说明:同上
#实例:
>>> import nltk
>>> nltk.corpus.brown.sents()
[['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'], ['The', 'jury', 'further', 'said', 'in', 'term-end', 'presentments', 'that', 'the', 'City', 'Executive', 'Committee', ',', 'which', 'had', 'over-all', 'charge', 'of', 'the', 'election', ',', '``', 'deserves', 'the', 'praise', 'and', 'thanks', 'of', 'the', 'City', 'of', 'Atlanta', "''", 'for', 'the', 'manner', 'in', 'which', 'the', 'election', 'was', 'conducted', '.'], ...]
>>> nltk.corpus.brown.words()
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
>>> len(nltk.corpus.brown.sents())
57340
>>> len(nltk.corpus.brown.words())
1161192