NLTK学习记录1:启程

使用NLTK

import nltk  #导入nltk
nltk.download()  #下载语料库

使用官方教程中的文本

from nltk.book import *

寻找特定词在文本中的上下文

text1.concordance("monstrous") #在text1中monstrous的上下文

依据上下文,寻找相似的词语

text1.similar("monstrous")
text2.similar("monstrous")

寻找多个词语在文本中的共同上下文

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

画出词语在文本中的位置信息图

text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])

对text文本进行计数

len(text3)   #文本text3的长度
sorted(set(text3))  #按顺序返回文本text3的全部词语
len(set(text3))  #text3的无重复词语数量、
len(set(text3)) / len(text3)  #text3的“词汇量丰富程度”
text3.count("smote")  #“smote”在text3中出现的次数

“text”本质上是一个词语的列表(list)

sent1 = ['Call', 'me', 'Ishmael', '.']   #定义一个sent1
['Monty', 'Python'] + ['and', 'the', 'Holy', 'Grail']  #连接两个list
sent4 + sent1  #连接两个list
sent1.append("Some")   #为sent1添加词语元素
text4[173]  #返回'awaken'
text4.index('awaken')  #返回索引值173
text5[16715:16735]

词语本身就是python中的字符串(string)

name = 'Monty'
name[:4]  #'Mont'
name * 2  #'MontyMonty'
name + '!'  #'Monty!'
' '.join(['Monty', 'Python'])  #'Monty Python'
'Monty Python'.split()  #['Monty', 'Python']

对于文本信息的简单统计

使用频率分布 frequency distribution

fdist1 = FreqDist(text1)   #生成text1的频率分布
fdist1.most_common(50)  #输出最常见的50个词语及其出现次数
fdist1['whale']  #输出特定词语‘whale’的出现次数

简单的词语筛选

V = set(text1)
long_words = [w for w in V if len(w) > 15]  #筛选出长词
sorted(long_words)

fdist5 = FreqDist(text5)
sorted(w for w in set(text5) if len(w) > 7 and fdist5[w] > 7) #筛选出高频长词

二元词语搭配

list(bigrams(['more', 'is', 'said', 'than', 'done']))  #返回[('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')],全部的二元搭配

text4.collocations()  #找到比我们根据单个词的频率预期更频繁出现的二元词
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容