NLTK (Natural Language Toolkit)

NTLK是著名的Python自然语言处理工具包,但是主要针对的是英文处理。NLTK配套有文档,有语料库,有书籍。

  • NLP领域中最常用的一个Python库
  • 开源项目
  • 自带分类、分词等功能
  • 强大的社区支持
  • 语料库,语言的实际使用中真是出现过的语言材料
  • http://www.nltk.org/py-modindex.html

在NLTK的主页详细介绍了如何在Mac、Linux和Windows下安装NLTK:http://nltk.org/install.html ,建议直接下载Anaconda,省去了大部分包的安装,安装NLTK完毕,可以import nltk测试一下,如果没有问题,还有下载NLTK官方提供的相关语料。

安装步骤:

  1. 下载NLTK包

    pip install nltk
  2. 运行Python,并输入下面的指令

     import nltk
    nltk.download()
  3. 弹出下面的窗口,建议安装所有的包 ,即all

  4. 测试使用:

语料库

nltk.corpus

import nltk
from nltk.corpus import brown # 需要下载brown语料库
# 引用布朗大学的语料库 # 查看语料库包含的类别
print(brown.categories()) # 查看brown语料库
print('共有{}个句子'.format(len(brown.sents())))
print('共有{}个单词'.format(len(brown.words())))

执行结果:

['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance', 'science_fiction']

共有57340个句子
共有1161192个单词

分词 (tokenize)

  • 将句子拆分成具有语言语义学上意义的词
  • 中、英文分词区别:
    • 英文中,单词之间是以空格作为自然分界符的
    • 中文中没有一个形式上的分界符,分词比英文复杂的多
  • 中文分词工具,如:结巴分词 pip install jieba
  • 得到分词结果后,中英文的后续处理没有太大区别
# 导入jieba分词
import jieba seg_list = jieba.cut("欢迎来到黑马程序员Python学科", cut_all=True)
print("全模式: " + "/ ".join(seg_list)) # 全模式 seg_list = jieba.cut("欢迎来到黑马程序员Python学科", cut_all=False)
print("精确模式: " + "/ ".join(seg_list)) # 精确模式

运行结果:

全模式: 欢迎/ 迎来/ 来到/ 黑马/ 程序/ 程序员/ Python/ 学科
精确模式: 欢迎/ 来到/ 黑马/ 程序员/ Python/ 学科

  

词形问题

  • look, looked, looking
  • 影响语料学习的准确度
  • 词形归一化

1. 词干提取(stemming)

示例:

# PorterStemmer
from nltk.stem.porter import PorterStemmer porter_stemmer = PorterStemmer()
print(porter_stemmer.stem('looked'))
print(porter_stemmer.stem('looking')) # 运行结果:
# look
# look

示例:

# SnowballStemmer
from nltk.stem import SnowballStemmer snowball_stemmer = SnowballStemmer('english')
print(snowball_stemmer.stem('looked'))
print(snowball_stemmer.stem('looking')) # 运行结果:
# look
# look

示例:

# LancasterStemmer
from nltk.stem.lancaster import LancasterStemmer lancaster_stemmer = LancasterStemmer()
print(lancaster_stemmer.stem('looked'))
print(lancaster_stemmer.stem('looking')) # 运行结果:
# look
# look

2. 词形归并(lemmatization)

  • stemming,词干提取,如将ing, ed去掉,只保留单词主干

  • lemmatization,词形归并,将单词的各种词形归并成一种形式,如am, is, are -> be, went->go

  • NLTK中的stemmer

    PorterStemmer, SnowballStemmer, LancasterStemmer

  • NLTK中的lemma

    WordNetLemmatizer

  • 问题

    went 动词 -> go, 走 Went 名词 -> Went,文特

  • 指明词性可以更准确地进行lemma

示例:

from nltk.stem import WordNetLemmatizer
# 需要下载wordnet语料库 wordnet_lematizer = WordNetLemmatizer()
print(wordnet_lematizer.lemmatize('cats'))
print(wordnet_lematizer.lemmatize('boxes'))
print(wordnet_lematizer.lemmatize('are'))
print(wordnet_lematizer.lemmatize('went')) # 运行结果:
# cat
# box
# are
# went

示例:

# 指明词性可以更准确地进行lemma
# lemmatize 默认为名词
print(wordnet_lematizer.lemmatize('are', pos='v'))
print(wordnet_lematizer.lemmatize('went', pos='v')) # 运行结果:
# be
# go

3. 词性标注 (Part-Of-Speech)

  • NLTK中的词性标注

    nltk.word_tokenize()

示例:

import nltk

words = nltk.word_tokenize('Python is a widely used programming language.')
print(nltk.pos_tag(words)) # 需要下载 averaged_perceptron_tagger # 运行结果:
# [('Python', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('widely', 'RB'), ('used', 'VBN'), ('programming', 'NN'), ('language', 'NN'), ('.', '.')]

4. 去除停用词

  • 为节省存储空间和提高搜索效率,NLP中会自动过滤掉某些字或词
  • 停用词都是人工输入、非自动化生成的,形成停用词表
  • 分类

    语言中的功能词,如the, is…

    词汇词,通常是使用广泛的词,如want

  • 中文停用词表

    中文停用词库

    哈工大停用词表

    四川大学机器智能实验室停用词库

    百度停用词列表

  • 其他语言停用词表

    http://www.ranks.nl/stopwords

  • 使用NLTK去除停用词

    stopwords.words()

示例:

from nltk.corpus import stopwords # 需要下载stopwords

filtered_words = [word for word in words if word not in stopwords.words('english')]
print('原始词:', words)
print('去除停用词后:', filtered_words) # 运行结果:
# 原始词: ['Python', 'is', 'a', 'widely', 'used', 'programming', 'language', '.']
# 去除停用词后: ['Python', 'widely', 'used', 'programming', 'language', '.']

5. 典型的文本预处理流程

示例:

import nltk
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords # 原始文本
raw_text = 'Life is like a box of chocolates. You never know what you\'re gonna get.' # 分词
raw_words = nltk.word_tokenize(raw_text) # 词形归一化
wordnet_lematizer = WordNetLemmatizer()
words = [wordnet_lematizer.lemmatize(raw_word) for raw_word in raw_words] # 去除停用词
filtered_words = [word for word in words if word not in stopwords.words('english')] print('原始文本:', raw_text)
print('预处理结果:', filtered_words)

运行结果:

原始文本: Life is like a box of chocolates. You never know what you're gonna get.
预处理结果: ['Life', 'like', 'box', 'chocolate', '.', 'You', 'never', 'know', "'re", 'gon', 'na', 'get', '.']

使用案例:

import nltk
from nltk.tokenize import WordPunctTokenizer sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
paragraph = "The first time I heard that song was in Hawaii on radio. I was just a kid, and loved it very much! What a fantastic song!" # 分句
sentences = sent_tokenizer.tokenize(paragraph)
print(sentences) sentence = "Are you old enough to remember Michael Jackson attending. the Grammys with Brooke Shields and Webster sat on his lap during the show?" # 分词
words = WordPunctTokenizer().tokenize(sentence.lower())
print(words)

输出结果:

['The first time I heard that song was in Hawaii on radio.', 'I was just a kid, and loved it very much!', 'What a fantastic song!']

['are', 'you', 'old', 'enough', 'to', 'remember', 'michael', 'jackson', 'attending', '.', 'the', 'grammys', 'with', 'brooke', 'shields', 'and', 'webster', 'sat', 'on', 'his', 'lap', 'during', 'the', 'show', '?']

NLTK与自然语言处理基础的更多相关文章

  1. NLTK在自然语言处理

    nltk-data.zip 本文主要是总结最近学习的论文.书籍相关知识,主要是Natural Language Pracessing(自然语言处理,简称NLP)和Python挖掘维基百科Infobox ...

  2. NLP系列(1)_从破译外星人文字浅谈自然语言处理基础

    作者:龙心尘 &&寒小阳 时间:2016年1月. 出处: http://blog.csdn.net/longxinchen_ml/article/details/50543337 ht ...

  3. 自然语言处理基础与实战(8)- 主题模型LDA理解与应用

    本文主要用于理解主题模型LDA(Latent Dirichlet Allocation)其背后的数学原理及其推导过程.本菇力求用简单的推理来论证LDA背后复杂的数学知识,苦于自身数学基础不够,因此文中 ...

  4. Python NLTK 自然语言处理入门与例程(转)

    转 https://blog.csdn.net/hzp666/article/details/79373720     Python NLTK 自然语言处理入门与例程 在这篇文章中,我们将基于 Pyt ...

  5. Python自然语言处理工具小结

    Python自然语言处理工具小结 作者:白宁超 2016年11月21日21:45:26 目录 [Python NLP]干货!详述Python NLTK下如何使用stanford NLP工具包(1) [ ...

  6. 《Python自然语言处理》

    <Python自然语言处理> 基本信息 作者: (美)Steven Bird    Ewan Klein    Edward Loper 出版社:人民邮电出版社 ISBN:97871153 ...

  7. 转-Python自然语言处理入门

      Python自然语言处理入门 原文链接:http://python.jobbole.com/85094/ 分享到:20 本文由 伯乐在线 - Ree Ray 翻译,renlytime 校稿.未经许 ...

  8. 自然语言处理(NLP)资源

    1.HMM学习最佳范例全文文档,百度网盘链接: http://pan.baidu.com/s/1pJoMA2B 密码: f7az 2.无约束最优化全文文档 -by @朱鉴 ,百度网盘链接:链接:htt ...

  9. 5本自然语言处理书单-附pdf

    文章发布于公号[数智物语] (ID:decision_engine),关注公号不错过每一篇干货. 自然语言处理(英语:Natural Language Processing,缩写作 NLP)是人工智能 ...

随机推荐

  1. 单一功能学习——百度AI之身份证识别

    以下内容基本是从官方接口文档复制过来的,附带自己封装的代码 时间:2018年4月4日 一.导入工具包 使用maven依赖: <dependency> <groupId>com. ...

  2. linux下利用inode删除指定文件文件

    本文主要介绍使用inode删除异常文件名的文件的方法,供大家参考: 在Linux中,有时候会遇到文件名是乱码或者是某些特殊中文的文件,这时候通过文件名就很难删除. 同时,对于linux中的任何一个文件 ...

  3. [IC]Lithograph(1)光刻技术分析与展望

    文章主体转载自: 1.zol摩尔定律全靠它 CPU光刻技术分析与展望 2.wiki:Extreme ultraviolet lithography 3.ITRS 2012 1. 光刻技术组成和关键点 ...

  4. laravel 修改重置密码模板

    Laravel里我们可以使用php artisan make:auth来生成一套默认的登陆注册重置邮箱的Authentication System,但是如何修改系统发送给用户的重置密码邮件的样式和内容 ...

  5. 编程技巧:使用整数同时进行多个true|false判断

    情景 : 假设需要判断某银行用户的其中一个账号(profileA),币种(Currency)为人民币(CNY),余额是否大于1,0000,然后进行某业务逻辑处理. 概述: 为了进行这种判断,需要判断/ ...

  6. 批量归一化batch_normalization

    为了解决在深度神经网络训练初期降低梯度消失/爆炸问题,Sergey loffe和Christian Szegedy提出了使用批量归一化的技术的方案,该技术包括在每一层激活函数之前在模型里加一个操作,简 ...

  7. (function($){...})(jQuery)与$(function(){...})区别

    $(function(){...}) 这种写法和jQuery(function(){...}),$(document).ready(function(){...})作用一样,表示文档载入后需要运行的代 ...

  8. BZOJ3529 [Sdoi2014]数表【莫比乌斯反演】

    Description 有一张 n×m 的数表,其第 i 行第 j 列(1 <= i <= n, 1 <= j <= m)的数值为 能同时整除 i 和 j 的所有自然数之和.给 ...

  9. BZOJ3687 简单题 【bitset】

    BZOJ3687 简单题 Description 小呆开始研究集合论了,他提出了关于一个数集四个问题: 1.子集的异或和的算术和. 2.子集的异或和的异或和. 3.子集的算术和的算术和. 4.子集的算 ...

  10. 《DSP using MATLAB》示例Example 8.15