原文链接:http://www.one2know.cn/nlp3/

  • 分词
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,WordNetLemmatizer

raw = '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_distance

def my_edit_distance(str1,str2):
m = len(str1) + 1
n = len(str2) + 1 # 创建二维表,初始化第一行和第一列
table = {}
for i in range(m): table[i,0] = i
for 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 1
table[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'}

NLP(三) 预处理的更多相关文章

  1. NLP 文本预处理

    1.不同类别文本量统计,类别不平衡差异 2.文本长度统计 3.文本处理,比如文本语料中简体与繁体共存,这会加大模型的学习难度.因此,他们对数据进行繁体转简体的处理. 同时,过滤掉了对分类没有任何作用的 ...

  2. DeepLearning (三) 预处理:主成分分析与白化

    [原创]Liu_LongPo 转载请注明出处 [CSDN]http://blog.csdn.net/llp1992 PCA算法前面在前面的博客中已经有介绍,这里简单在描述一下,更详细的PCA算法请参考 ...

  3. 百度NLP三面

    首先,面试官根据项目经验进行提问,主要是自然语言处理相关的问题:然后写代码题,字符串处理和数字运算居多:再者是一些语言基础知识,百度用的linux平台,C++和python居多.下面列出我面试中的一些 ...

  4. 史上最详尽的NLP预处理模型汇总

    文章发布于公号[数智物语] (ID:decision_engine),关注公号不错过每一篇干货. 转自 | 磐创AI(公众号ID:xunixs) 作者 | AI小昕 编者按:近年来,自然语言处理(NL ...

  5. 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作

    目录 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 NLP相关的文本预处理 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 之所以心血来潮想写这篇博客,是因为最近在关注N ...

  6. C预编译, 预处理, C/C++头文件, 编译控制,

    在所有的预处理指令中,#Pragma 指令可能是最复杂的了,它的作用是设定编译器的状态或者是指示编译器完成一些特定的动作.#pragma指令对每个编译器给出了一个方法,在保持与C和C++语言完全兼容的 ...

  7. C中的预编译宏定义

     可以用宏判断是否为ARC环境 #if _has_feature(objc_arc) #else //MRC #endif C中的预编译宏定义 -- 作者: infobillows 来源:网络 在将一 ...

  8. 一些基础的.net用法

    一.using 用法 using 别名设置 using 别名 = System.web 当两个不同的namespace里有同名的class时.可以用 using aclass = namespace1 ...

  9. 学习笔记之自然语言处理(Natural Language Processing)

    自然语言处理 - 维基百科,自由的百科全书 https://zh.wikipedia.org/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7 ...

随机推荐

  1. bootstrap datatable editor 扩展

    需求: a. 表单样式更改. b. 表单大小更改. 思路: a. 通过设置modal css更改样式和大小.缺点,全局性的更改. b. 更改bootstrap-editor,可以通过某种方式将参数传入 ...

  2. Jquery第二次考核

    1. 名词解释 实例对象:var p1=new Person();  p1就是实例对象 构造:function Person(){} 原型对象:在 JavaScript 中,每当定义一个对象(函数也是 ...

  3. handlerMapping的初始化以及查找handler

    前提:HttpServletBean初始化了一些servlet配置,接着FrameWorkServlet创建了WebApplicationContext,最后DispatcherServlet初始化一 ...

  4. 【Python3爬虫】当爬虫碰到表单提交,有点意思

    一.写在前面 我写爬虫已经写了一段时间了,对于那些使用GET请求或者POST请求的网页,爬取的时候都还算得心应手.不过最近遇到了一个有趣的网站,虽然爬取的难度不大,不过因为表单提交的存在,所以一开始还 ...

  5. 入门MySQL——架构篇

    前言:  上篇文章我们介绍了入门MySQL的基本概念,看完上篇文章,相信你应该了解MySQL的前世今生了吧.本篇文章将带你从架构体系来学习MySQL.我认为学习MySQL架构体系应该是入门阶段必须的, ...

  6. firewalld防火墙命令规则设置

    1.firewalld的基本使用 启动/关闭: systemctl start/stop firewalld 查看状态: systemctl status firewalld 开机启用/禁用 : sy ...

  7. 【JDK】JDK源码分析-TreeMap(2)

    前文「JDK源码分析-TreeMap(1)」分析了 TreeMap 的一些方法,本文分析其中的增删方法.这也是红黑树插入和删除节点的操作,由于相对复杂,因此单独进行分析. 插入操作 该操作其实就是红黑 ...

  8. 【Android】Field requires API level 4 (current min is 1): android.os.Build.VERSION#SDK_INT

    刚遇到了这个问题: Field requires API level 4 (current min is 1): android.os.Build.VERSION#SDK_INT 解决方法: 修改 A ...

  9. EasyUI combobox下拉列表实现搜索过滤(模糊匹配)

    项目中的某个下拉列表长达200多个项,这么巨大的数量一个一个找眼镜都得看花,于是就得整了个搜索功能.看网上别人帖子有只能前缀匹配的方案,但只能前缀匹配的话用起来也不是很方便.于是就记录一下模糊匹配的方 ...

  10. MySQL-5.7.21非图形化下载、安装、连接问题记录

    1.安装包下载链接:https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.21-winx64.zip 官网:https://www.mysql.co ...