NLTK——NLP编程的基础工具

来源:互联网 发布:淘宝运费险咨询电话 编辑:程序博客网 时间:2024/05/01 11:39

1.NLTK入门

1.下载NLTK,可用pip install nltk,anaconda本身已经有NLTK了,可直接使用。

2.下载NLTK的范例文本,

import nltknltk.download()#下载Collections下的book

3.使用基本函数

3.1 concordance 查找指定词

from nltk.book import *text1.concordance("monstrous")

3.2 similar 查找与monstrous相关的词,比如出现的上下文相同

text1.silimar("monstrous")

3.3 common_contexts 共用2个或2个以上词汇的上下文

text2.common_contexts(["monstrous","very"])

3.4 dispersion_plot 单词在文章中的分布

text4.dispersion_plot(["citizens","demoracy","freedom","duties","America"])//需要用到Numpy和Matplotlib,好像Anaconda都有的

这里写图片描述
3.5 generate 产生随机文本

text3.generate()//重复使用源文本中常见的单词和短语,从而使我们能感觉到它的风格和内容。

3.6.1 计数词汇

len(text3)//创世纪有44764个单词和标点符号,也被称作标识符sorted(set(text3))//用sorted包裹set(text3),得到一个词汇条目的排序表,以各种标点符号开始,然后接着是以A开头的词汇。大写单词排在小写单词前面。通过求集合中各种项目的个数,可以间接获得词汇表的大小。用len获得。len(set(text3))//2789

3.6.2 测量词汇丰富度

print len(text3)/len(set(text3))  #16.050197... 每个词平均出现了16次

3.6.3 count 计算一个词在文本中出现的次数,和百分比

text3.count("smote")              #5100*text4.count('a')/len(text4)   #1.4643....

4.将文本当做词链表

链表的连接,append添加元素,索引(下标),index,切片

sent1=['Call','me','Ishmael','.']print len(sent1)   #4lexical_diversity(sent1)  #1.0  词汇分离图?sent2=['The','family','of','Dashwood','had','long','been','settled','in','Sussex','.']sent3=['In','the','beginning','God','created','the','heaven','and','the','earth','.']print sent2+sent3  #连接,将多个链表组合为一个链表#['The', 'family', 'of', 'Dashwood', 'had', 'long', 'been', 'settled', 'in', 'Sussex', '.', 'In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']sent1.append('some')print sent1  #sent1=['Call','me','Ishmael','.','some']print text4[173]  #'awaken'print text4.index('awaken')   #173  第一次出现的位置
#切片(获取子链表)print text5[16715:16735]print text6[1600:1625]
#字符串name='Monty'print name[0]     #'M'print name[:4]    #'Mont'#乘法和加法print name*2      #'MontyMonty'print name+'!'    #'Monty!'
#词链表组合成单个字符串,字符串拆分成词链表''.join(['Monty',' Python'])    #'Monty Python''Monty Python'.split()          #['Monty','Python']print 'Monty Python'.split('y') #['Mont', ' P', 'thon']

5.简单的统计

5.1 利用FreqDist寻找《白鲸记》中最常见的50个词fdist1 = FreqDist(text1)print fdist1                        #<FreqDist with 19317 samples and 260819 outcomes>vocabulary1 = fdist1.keys()print vocabulary1[:50]fdist1['whale']                     #906fdist.plot(50,cumulative=True)      #累积分布图

最常用50个单词的累积频率图,这些词占了所有标识符的近一半
最常用50个单词的累积频率图,这些词占了所有标识符的近一半
高频词对我们并没有什么帮助。(全是 a,the ,of, to 这种)

5.2 统计只出现一次的词:hapaxes

fdist1.hapaxes()           #9000多个,然并卵

5.3 细粒度的选择词

#找出文本词汇表中长度超过15的词V=set(text1)long_words=[w for w in V if (len(w)>15)sorted(long_words)#找出文本词汇表中长度超过7,出现频率超过7次的词fdist5=FreqDist(text5)sorted([w for w in set(text5) if len(w)>7 and fdist5[w]>7])

6. 词语搭配和双连词

6.1 提取双连词 bigrams(),collocations()

bigrams(['more','is','said','than','done'])text4.collocations()text8.collocations()

7.计算其他东西(如词长)

[len(w) for w in text1]fdist=FreqDist([len(w) for w in text1])print fdist         #260819print fdist.keys()        #把词长从频率高到少排列,keys函数似乎没有作用print fdist.max(),fdist[3],fdist.freq(3)   # 3,50223, 0.1925588...

8. NLTK中频率分布定义的函数

例子 描述 fdist=FreqDist(samples) 创建包含指定样本的频率分布 fdist.inc(sample) 增加样本 fdist[‘monstrous’] 计数给定样本出现的次数 fdist.freq(‘monstrous’) 给定样本的频率 fdist.N() 样本总数 fdist.keys() 以频率递减顺序排序的样本链表 for sample in fdist: 以频率递减的顺序遍历样本 fdist.max() 数值最大的样本 fdist.tabulate() 绘制频率分布表 fdist.plot() 绘制频率分布图 fdist.plot(cumulative=True) 绘制累计频率分布图 fdist < fdist2 测试样本在fdist中出现的频率是否小于fdist2

9. 决策和控制

print "sent7:",sent7print [w for w in sent7 if len(w)<4]print [w for w in sent7 if len(w)<=4]print [w for w in sent7 if len(w)==4]

9.1词汇比较运算符

函数 含义 s.startswith(t) 测试s是否以t开头 s.endswith(t) 测试是否以t结尾 t in s 测试s中是否含有t s.islower() 测试s中所有字符是否都是小写字母 s.isupper() 测试s中所有字符是否都是大写字母 s.isalpha() 测试s中所有字符是否都是字母 s.isalnum() 测试s中是否都是字母或数字 s.isdigit() 测试s中所有字符是否都是数字 s.istitle() 测试s是否首字母大写(s中所有的词都首字母大写)
print sorted([w for w in set(text1) if w.endswith('ableness')])print sorted([term for term in set(text4) if 'gnt' in  term])print sorted([item for item in set(text6) if item.istitle()])print sorted([item for item in set(sent7) if item.isdigit()])

9.2对每个元素进行操作
表达形式为[f(w) for …] 或 [w.f() for…] f是一个函数用来计算词长或将字母转换为大写等

[len(w) for w in text1][w.upper() for w in text1]len(text1)                                        #260819len(set(text1))                                   #19317len(set([word.lower() for word in text1]))         #17231,不重复计算大小写不同的词len(set([word.lower() for word in text1 if word.alpha()]))   #16948 过滤掉非字母元素tricky=sorted([w for w in set(text2) if 'cie' in w or 'cei' in w])for word in tricky:    print word,

10. 自动理解自然语言

10.1 词义消歧
10.2 指代消解
等等

0 0