NLP(三) 预处理
- 分词
from nltk.tokenize import LineTokenizer,SpaceTokenizer,TweetTokenizer
from nltk import word_tokenize# 根据行分词,将每行作为一个元素放到list中
lTokenizer = LineTokenizer()
print('Line tokenizer output :',lTokenizer.tokenize('hello hello\npython\nworld'))# 根据空格分词
rawText = 'hello python,world'
sTokenizer = SpaceTokenizer()
print('Space tokenizer output :',sTokenizer.tokenize(rawText))# word_tokenize分词
print('Word tokenizer output :',word_tokenize(rawText))# 能使特殊符号不被分开
tTokenizer = TweetTokenizer()
print('Tweet tokenizer output :',tTokenizer.tokenize('This is a cooool #dummysmiley: :-) :-p <3'))
输出:
Line tokenizer output : ['hello hello', 'python', 'world']
Space tokenizer output : ['hello', 'python,world']
Word tokenizer output : ['hello', 'python', ',', 'world']
Tweet tokenizer output : ['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-p', '<3']
- 词干提取
去除词的后缀,输出词干,如wanted=>want
from nltk import PorterStemmer,LancasterStemmer,word_tokenize# 创建raw并将raw分词
raw = 'he wants to be loved by others'
tokens = word_tokenize(raw)
print(tokens)# 输出词干
porter = PorterStemmer()
pStems = [porter.stem(t) for t in tokens]
print(pStems)# 这种方法去除的多,易出错
lancaster = LancasterStemmer()
lTems = [lancaster.stem(t) for t in tokens]
print(lTems)
输出:
['he', 'wants', 'to', 'be', 'loved', 'by', 'others']
['he', 'want', 'to', 'be', 'love', 'by', 'other']
['he', 'want', 'to', 'be', 'lov', 'by', 'oth']
- 词形还原
词干提取只是去除后缀,词形还原是对应字典匹配还原
from nltk import word_tokenize,PorterStemmer,WordNetLemmatizerraw = 'Tom flied kites last week in Beijing'
tokens = word_tokenize(raw)# 去除后缀
porter = PorterStemmer()
stems = [porter.stem(t) for t in tokens]
print(stems)# 还原器:字典找到才还原,特殊大写词不还原
lemmatizer = WordNetLemmatizer()
lemmas = [lemmatizer.lemmatize(t) for t in tokens]
print(lemmas)
输出:
['tom', 'fli', 'kite', 'last', 'week', 'in', 'beij']
['Tom', 'flied', 'kite', 'last', 'week', 'in', 'Beijing']
- 停用词
古登堡语料库:18个未分类的纯文本
import nltk
from nltk.corpus import gutenberg
# nltk.download('gutenberg')
# nltk.download('stopwords')
print(gutenberg.fileids())
# print(stopwords)# 获得bible-kjv.txt的所有单词,并过滤掉长度<3的单词
gb_words = gutenberg.words('bible-kjv.txt')
words_filtered = [e for e in gb_words if len(e) >= 3]# 加载英文的停用词,并用它过滤
stopwords = nltk.corpus.stopwords.words('english')
words = [w for w in words_filtered if w.lower() not in stopwords]# 处理的词表和未做处理的词表 词频的比较
fdistPlain = nltk.FreqDist(words)
fdist = nltk.FreqDist(gb_words)# 观察他们的频率分布特征
print('Following are the most common 10 words in the bag')
print(fdistPlain.most_common(10))
print('Following are the most common 10 words in the bag minus the stopwords')
print(fdist.most_common(10))
输出:
['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', 'shakespeare-caesar.txt', 'shakespeare-hamlet.txt', 'shakespeare-macbeth.txt', 'whitman-leaves.txt']
Following are the most common 10 words in the bag
[('shall', 9760), ('unto', 8940), ('LORD', 6651), ('thou', 4890), ('thy', 4450), ('God', 4115), ('said', 3995), ('thee', 3827), ('upon', 2730), ('man', 2721)]
Following are the most common 10 words in the bag minus the stopwords
[(',', 70509), ('the', 62103), (':', 43766), ('and', 38847), ('of', 34480), ('.', 26160), ('to', 13396), ('And', 12846), ('that', 12576), ('in', 12331)]
- 编辑距离 Levenshtein_distance
从一个字符串变到另外一个字符串所需要最小的步骤,衡量两个字符串的相似度
动态规划算法:创建一个二维表,若相等,则=左上;否则=min(左,上,左上)+1
填完表计算编辑距离和相似度:
设两个字符串的长度分别是m,n,填的二维表为A
则
编辑距离 = A[m][n]
相似度 = 1 - 编辑距离/max(m,n)
代码实现:
from nltk.metrics.distance import edit_distancedef my_edit_distance(str1,str2):m = len(str1) + 1n = len(str2) + 1# 创建二维表,初始化第一行和第一列table = {}for i in range(m): table[i,0] = ifor j in range(n): table[0,j] = j# 填表for i in range(1,m):for j in range(1,n):cost = 0 if str1[i-1] == str2[j-1] else 1table[i,j] = min(table[i,j-1]+1,table[i-1,j]+1,table[i-1,j-1]+cost)return table[i,j],1-table[i,j]/max(i,j)print('My Algorithm :',my_edit_distance('aboard','abroad'))
print('NLTK Algorithm :',edit_distance('aboard','abroad'))
输出:
My Algorithm : (2, 0.6666666666666667)
NLTK Algorithm : 2
- 提取两个文本共有词汇
story1 = open('story1.txt','r',encoding='utf-8').read()
story2 = open('story2.txt','r',encoding='utf-8').read()# 删除特殊字符,所有字符串小写
story1 = story1.replace(',',' ').replace('\n',' ').replace('.',' ').replace('"',' ')\.replace("'",' ').replace('!',' ').replace('?',' ').casefold()
story2 = story2.replace(',',' ').replace('\n',' ').replace('.',' ').replace('"',' ')\.replace("'",' ').replace('!',' ').replace('?',' ').casefold()# 分词
story1_words = story1.split(' ')
story2_words = story2.split(' ')# 去掉重复词
story1_vocab = set(story1_words)
story2_vocab = set(story2_words)# 找共同词
common_vocab = story1_vocab & story2_vocab
print('Common Vocabulary :',common_vocab)
输出:
Common Vocabulary : {'', 'got', 'for', 'but', 'out', 'you', 'caught', 'so', 'very', 'away', 'could', 'to', 'not', 'it', 'a', 'they', 'was', 'of', 'and', 'said', 'ran', 'the', 'saw', 'have'}
转载于:https://www.cnblogs.com/peng8098/p/nlp_3.html
NLP(三) 预处理相关推荐
- NLP文本预处理:步骤、示例 | 附github源码
点击关注我哦 一篇文章带你了解NLP文本预处理:步骤.示例 | 附github源码 注:关注[小白玩转Python]公众号,后台回复[NLP文本预处理],可以获取完整源码以及项目所需数据集. 文本数据 ...
- NLP数据预处理与词嵌入
NLP数据预处理与词嵌入 NLP数据预处理 读入语料库 首先准备一个语料库,实际上就是一个 txt 文件,这里用的是小说 time machine ,该语料库比较短小,仅有 ~3000 行,~3000 ...
- NLP | 文本预处理
一.文本预处理 作用:文本语料在输送给模型前一般需要一系列的预处理工作,才能符合模型输入的要求,如:将文本转化成模型需要的张量,规范张量的尺寸等,而且科学的文本预处理环节还将有效指导模型超参数的选择, ...
- NLP —— 文本预处理
一.分词简介 分词就是将连续的字序列按照一定的规范重新组合成词序列的过程.我们知道,在英文的行文中,单词之间是以空格作为自然分界符的,而中文只是字.句和段能通过明显的分界符来简单划界,唯独词没有一个形 ...
- 英伟达“暴力碾压”谷歌:53分钟训练完BERT,2.2毫秒完成推理,创下NLP三项新纪录...
边策 发自 凹非寺 量子位 报道 | 公众号 QbitAI AI硬(he)件(dan)厂商英伟达今天宣布,他们在NLP模型上取得了三大突破,为今后会话AI的落地应用铺平了道路. 英伟达用自己的硬件与 ...
- 中文自然语言处理(NLP)(三)运用python jieba模块计算知识点当中关键词的词频
前两次链接:中文自然语言处理(NLP)(一)python jieba模块的初步使用 中文自然语言处理(NLP)(二)python jieba模块的进一步学习和xlrd模块 续上次的随笔之后 ...
- 美团算法 SP | NLP 三面复盘
作者 | 甄同学 编辑 | NewBeeNLP 面试锦囊之面经分享系列,持续更新中 后台回复『面试』加入讨论组交流噢 一面 时间50mins 自我介绍. 聊天.(面试体验好的面试官都是会聊天几句的 ...
- nlp文本预处理构建词汇表
文本预处理: 建立字典,将每个词或者字映射到一个唯一的索引(index) 将文本从词或者字的序列转换为索引的序列,方便输入模型 并且label同步映射 import jsonfrom ner impo ...
- NLP数据预处理的一般方法
文章目录 一.前言 二.实现方法 一.前言 数据预处理一般包括如下几个步骤 读取数据[txt.csv] 拆分输入.输出数据 缺失数据处理[删除.插值] 字符串类型的数据处理[稀疏矩阵.embeddin ...
- 当GCN遇见NLP(三) Tensor Graph Convolutional Networks for Text Classification,AAAI2020
文章目录 1.Introduction 2.Model 2.1 Graph Tensor 2.2 Text graph tensor construction Semantic-based graph ...
最新文章
- 公开课 | 人脸识别的最新进展以及工业级大规模人脸识别实践探讨
- 大数据虚拟化:VMware正在虚拟化Hadoop
- 图灵赠书——程序员11月书单
- 应用的大数据:医疗保健的经济学
- [引]生成加密和解密的密钥
- 华为 MindSpore 喊你来开发 10 大 AI 模型,260 万奖金怎能没你一份?
- 打印机提示更换墨盒,但打印字仍很清晰,打印机设置还能用很久
- 《无痛苦N-S方程笔记》第二章知识点框架
- 电子工程师最全面试题大全
- 沪深300指数的跟踪基金最近1年收益排名
- 国内首款PCB资料分析软件,华秋DFM使用介绍
- 军团指挥官(权限题)
- 漫谈程序员系列 软件开发的十八般乐趣
- iptables结合ipset禁止国外IP进行访问
- 教你如何用shell脚本输出菱形
- 终极WordPress页面构建器:WPBakery
- python pexpect使用介绍
- 个人用户如何保证企业邮箱安全?【163企业邮箱注册】
- 脑电数据分析方法与应用实例简介-EEG Processing and Feature 1
- 华师大数据科学考研_华东师范大学数据科学与工程学院硕士研究生录取名单公示...
热门文章
- koolshare离线插件下载_还记得那个提速8倍的IDEA插件吗?VS Code版本也发布啦
- 华军java_Java SE Runtime Environment 8
- Struts2→MCV、环境搭建第一个样例、工作原理、核心文件、XML中常用元素、通配符、action后缀、action接收参数、result、标签
- b站学python_Python爬虫学习教程 bilibili网站视频爬取!【附源码】
- 计算机组成原理—主存储器与cpu的连接
- 试用 P、V操作描述下列理发师和顾客之间的同步问题
- UnityShader29:模板测试
- 利用拉普拉斯滤波器提取图像边缘,实现图像锐化
- matlab 纹理映射
- c#实现linux中gzip压缩解压缩算法:byte[]字节数组,文件,字符串,数据流的压缩解压缩