参考文章:自然语言处理库——NLTK_满腹的小不甘-程序员秘密
NLP 自然语言处理的开发环境搭建_村雨遥-程序员秘密_nlp开发
NLTK :: Natural Language Toolkit(官网)
手动下载并安装nltk_data_justlpf的专栏-程序员秘密
GitHub - nltk/nltk_data: NLTK Data
目录
3. 词汇规范化(Lexicon Normalization)
- Natural Language Toolkit,自然语言处理工具包,在NLP领域中,最常使用的一个Python库。
- NLTK是一个开源的项目,包含:Python模块,数据集和教程,用于NLP的研究和开发。
- NLTK由Steven Bird和Edward Loper在宾夕法尼亚大学计算机和信息科学系开发。
- NLTK包括图形演示和示例数据。其提供的教程解释了工具包支持的语言处理任务背后的基本概念。
NLTK(www.nltk.org)是在处理预料库、分类文本、分析语言结构等多项操作中最长遇到的包。其收集的大量公开数据集、模型上提供了全面、易用的接口,涵盖了分词、词性标注(Part-Of-Speech tag, POS-tag)、命名实体识别(Named Entity Recognition, NER)、句法分析(Syntactic Parse)等各项 NLP 领域的功能。
NLTK能干啥?
- 搜索文本
- 单词搜索:
- 相似词搜索;
- 相似关键词识别;
- 词汇分布图;
- 生成文本;
- 计数词汇
NLTK设计目标
- 简易性;
- 一致性;
- 可扩展性;
- 模块化;
NLTK中的语料库
- 古腾堡语料库:
gutenberg
;- 网络聊天语料库:
webtext
、nps_chat
;- 布朗语料库:
brown
;- 路透社语料库:
reuters
;- 就职演说语料库:
inaugural
;- 其他语料库;
文本语料库结构
- isolated: 独立型;
- categorized:分类型;
- overlapping:重叠型;
- temporal:暂时型;
基本语料库函数
条件频率分布
- Python安装
- NLTK系统安装
- 自动下载nltk_data一般会失败, 手动下载并配置nltk_data, 参考:手动下载并安装nltk_data_justlpf的专栏-程序员秘密
文本是由段落(Paragraph)构成的,段落是由句子(Sentence)构成的,句子是由单词构成的。切词是文本分析的第一步,它把文本段落分解为较小的实体(如单词或句子),每一个实体叫做一个Token,Token是构成句子(sentence )的单词、是段落(paragraph)的句子。NLTK能够实现句子切分和单词切分两种功能。
把段落切分成句子:
from nltk.tokenize import sent_tokenize
text="""Hello Mr. Smith, how are you doing today? The weather is great, and
city is awesome.The sky is pinkish-blue. You shouldn't eat cardboard"""
tokenized_text=sent_tokenize(text)
print(tokenized_text)
'''
结果:
['Hello Mr. Smith, how are you doing today?',
'The weather is great, and city is awesome.The sky is pinkish-blue.',
"You shouldn't eat cardboard"]
'''
句子切分成单词:
import nltk
sent = "I am almost dead this time"
token = nltk.word_tokenize(sent)
# 结果:token['I','am','almost','dead','this','time']
对切词的处理,需要移除标点符号和移除停用词和词汇规范化。
对每个切词调用该函数,移除字符串中的标点符号,string.punctuation包含了所有的标点符号,从切词中把这些标点符号替换为空格。
import string
"""移除标点符号"""
if __name__ == '__main__':
# 方式一
# s = 'abc.'
text_list = "Hello Mr. Smith, how are you doing today? The weather is great, and city is awesome."
text_list = text_list.translate(str.maketrans(string.punctuation, " " * len(string.punctuation))) # abc
print("s: ", text_list)
# 方式二
english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']
text_list = [word for word in text_list if word not in english_punctuations]
print("text: ", text_list)
停用词(stopword)是文本中的噪音单词,没有任何意义,常用的英语停用词,例如:is, am, are, this, a, an, the。NLTK的语料库中有一个停用词,用户必须从切词列表中把停用词去掉。
import nltk
from nltk.corpus import stopwords
# nltk.download('stopwords')
# Downloading package stopwords to
# C:\Users\Administrator\AppData\Roaming\nltk_data\corpora\stopwords.zip.
# Unzipping the stopwords.zip
"""移除停用词"""
stop_words = stopwords.words("english")
if __name__ == '__main__':
text = "Hello Mr. Smith, how are you doing today? The weather is great, and city is awesome."
word_tokens = nltk.tokenize.word_tokenize(text.strip())
filtered_word = [w for w in word_tokens if not w in stop_words]
print("word_tokens: ", word_tokens)
print("filtered_word: ", filtered_word)
'''
word_tokens:['Hello', 'Mr.', 'Smith', ',', 'how', 'are', 'you', 'doing', 'today', '?',
'The', 'weather', 'is', 'great', ',', 'and', 'city', 'is', 'awesome', '.']
filtered_word:['Hello', 'Mr.', 'Smith', ',', 'today', '?', 'The', 'weather', 'great', ',', 'city', 'awesome', '.']
'''
词汇规范化是指把词的各种派生形式转换为词根,在NLTK中存在两种抽取词干的方法porter和wordnet。
利用上下文语境和词性来确定相关单词的变化形式,根据词性来获取相关的词根,也叫lemma,结果是真实的单词。
基于字典的映射。nltk中要求手动注明词性,否则可能会有问题。因此一般先要分词、词性标注,再词性还原。
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
lemmatizer.lemmatize('leaves')
# 输出:'leaf'
从单词中删除词缀并返回词干,可能不是真正的单词。
# 基于Porter词干提取算法
from nltk.stem.porter import PorterStemmer
porter_stemmer = PorterStemmer()
porter_stemmer.stem(‘maximum’)
# 基于Lancaster 词干提取算法
from nltk.stem.lancaster import LancasterStemmer
lancaster_stemmer = LancasterStemmer()
lancaster_stemmer.stem(‘maximum’)
# 基于Snowball 词干提取算法
from nltk.stem import SnowballStemmer
snowball_stemmer = SnowballStemmer(“english”)
snowball_stemmer.stem(‘maximum’)
from nltk.stem.wordnet import WordNetLemmatizer # from nltk.stem import WordNetLemmatizer
lem = WordNetLemmatizer() # 词形还原
from nltk.stem.porter import PorterStemmer # from nltk.stem import PorterStemmer
stem = PorterStemmer() # 词干提取
word = "flying"
print("Lemmatized Word:",lem.lemmatize(word,"v"))
print("Stemmed Word:",stem.stem(word))
'''
Lemmatized Word: fly
Stemmed Word: fli
'''
词性(POS)标记的主要目标是识别给定单词的语法组,POS标记查找句子内的关系,并为该单词分配相应的标签。
sent = "Albert Einstein was born in Ulm, Germany in 1879."
tokens = nltk.word_tokenize(sent)
tags = nltk.pos_tag(tokens)
'''
[('Albert', 'NNP'), ('Einstein', 'NNP'), ('was', 'VBD'), ('born', 'VBN'),
('in', 'IN'), ('Ulm', 'NNP'), (',', ','), ('Germany', 'NNP'), ('in', 'IN'), ('1879', 'CD'), ('.', '.')]
'''
查看一个单词的同义词集用synsets(); 它有一个参数pos,可以指定查找的词性。WordNet接口是面向语义的英语词典,类似于传统字典。它是NLTK语料库的一部分。
import nltk
nltk.download('wordnet') # Downloading package wordnet to C:\Users\Administrator\AppData\Roaming\nltk_data...Unzipping corpora\wordnet.zip.
from nltk.corpus import wordnet
word = wordnet.synsets('spectacular')
print(word)
# [Synset('spectacular.n.01'), Synset('dramatic.s.02'), Synset('spectacular.s.02'), Synset('outstanding.s.02')]
print(word[0].definition())
print(word[1].definition())
print(word[2].definition())
print(word[3].definition())
'''
a lavishly produced performance
sensational in appearance or thrilling in effect
characteristic of spectacles or drama
having a quality that thrusts itself into attention
'''
把切分好的词表进行词频排序(按照出现次数排序):
all_words = nltk.FreqDist(w.lower() for w in nltk.word_tokenize( "I'm foolish foolish man" ))
print (all_words.keys())
all_words.plot()
dict_keys(["'m", 'man', 'i', 'foolish']):
只考虑最高频率的两个词,并且绘制累积图:
all_words.plot(
2
, cumulative
=
True
)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018-9-28 22:21
# @Author : Manu
# @Site :
# @File : python_base.py
# @Software: PyCharm
from __future__ import division
import nltk
import matplotlib
from nltk.book import *
from nltk.util import bigrams
# 单词搜索
print('单词搜索')
text1.concordance('boy')
text2.concordance('friends')
# 相似词搜索
print('相似词搜索')
text3.similar('time')
#共同上下文搜索
print('共同上下文搜索')
text2.common_contexts(['monstrous','very'])
# 词汇分布表
print('词汇分布表')
text4.dispersion_plot(['citizens', 'American', 'freedom', 'duties'])
# 词汇计数
print('词汇计数')
print(len(text5))
sorted(set(text5))
print(len(set(text5)))
# 重复词密度
print('重复词密度')
print(len(text8) / len(set(text8)))
# 关键词密度
print('关键词密度')
print(text9.count('girl'))
print(text9.count('girl') * 100 / len(text9))
# 频率分布
fdist = FreqDist(text1)
vocabulary = fdist.keys()
for i in vocabulary:
print(i)
# 高频前20
fdist.plot(20, cumulative = True)
# 低频词
print('低频词:')
print(fdist.hapaxes())
# 词语搭配
print('词语搭配')
words = list(bigrams(['louder', 'words', 'speak']))
print(words)
在Intellij IEDA 做 java和 c/c++混编 最近公司项目做语音录音,涉及导c++和java混合开发。研究了几天混编知识,这里总结下,记录下自己的劳动成果。1. 什么是JNI? JNI是Java Native Interface的缩写,它提...
本文主要介绍了IDEA社区版如何创建一个spring boot 项目。主要有两种方式,一种使基于插件,一种就是通过spring官网中的网页创建。
K-means算法是硬聚类算法,是典型的基于原型的目标函数聚类方法的代表,它是数据点到原型的某种距离作为优化的目标函数,利用函数求极值的方法得到迭代运算的调整规则。K-means算法以偶是距离作为相似度测度,它是求对应某一初始聚类中心向量V最优分类,使得评价指标J最小。算法采用误差平方和准则函数作为聚类准则函数 K-means聚类算法采用的是将N*P的矩阵X划分为K个类,使得类内对象之间
安装版本:turnserver-3.2.3.95.tar.gz 系统环境:AWS ec2 一、下载必要库 sudo yum install -y make auomake gcc cc gcc-c++ wget sudo yum install -y openssl-devel libevent libevent-devel mysql-devel mysql-server...
YOLO V4论文解读一、YOLOV3回顾二、YOLOV4中三、Bag of freebies数据扩充:模拟对象遮挡:结合多幅图像进行数据扩充:解决类别不平衡:label smoothingbbox:Yolov4-use:四、Bag of specials1、 enhance receptive field(扩充接受阈): SPP, ASPP, RFB2、 attention module:3、feature integration:(特征集成)4、activation function:5、post-pr
在torch里面,view函数相当于numpy的reshape,来看几个例子:a = torch.arange(1, 17) # a's shape is (16,)a.view(4, 4) # output belowtensor([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]])[torch.FloatTensor of size 4x4]...
前言近些年随着云技术的发展,越来越多的用户选择使用云技术来代替将传统的 IT 基础设施。在云技术发展的早期,业界的关注点集中在虚拟化、分布式、存储等 Iaas 方面的技术。但是随着“云原生”概念的提出,大家的注意力开始转移到如何构建更加适合云环境运行的应用上来。“什么样的架构才是适合在云环境中运行”是一个非常大的问题,在此先不展开讨论,而是到 CNCF 对云原生的定义中寻找答案:云原生技术有利于各组织在公有云、私有云和混合云等新型动态环境中,构建和运行可弹性扩展的应用。云原生的代表技术包括容器、服务
免费视频教程和源码:https://www.bilibili.com/video/av84573813/1. 开始使用CefSharp在Winform中嵌入网页2. 解决重复打开Cefsharp出现崩溃的问题3. 使用本地网页,cefsharp调用javascript代码实现打开CefSharp的调试工具打开本地命令行窗口获取电脑信息关闭窗体4. 把网站打包成window...
Python 打算删除大量涉及像C和C++语言那样的复杂内存管理。当对象离开范围,就会被自动垃圾收集器回收。然而,对于由 Python 开发的大型且长期运行的系统来说,内存管理是不容小觑的事情。在这篇博客中,我将会分享关于减少 Python 内存消耗的方法和分析导致内存消耗/膨胀根源的问题。这些都是从实际操作中总结的经验,我们正在构建 Datos IO 的 RecoverX 分布式备份和恢复平
2019独角兽企业重金招聘Python工程师标准>>> ...
第一个常见看法是:python和basic差不多应该是容易学,但是功能弱的语言basic是好多人的年幼时的回忆了,gvbasic,gwbasic,qbaisc,各种版本把很多人带入了快乐的世界里面。但是很多人都会用了一段时间basic之后就把它废置了,因为觉得除了能够用来play,功能太少。即便是vb,也是功能不甚完善的,很多地方要依靠其他语言写的组件和直接调用api来完成功能。而python由于...