书籍地址:http://www.nltk.org/book/
1. Computing with Language: Texts and Words
1.1 入门准备
Anaconda版本的python自带nltk,但是没有样例数据,需要下载:
import nltk
nltk.download()
但是由于网络问题,会遇到下载失败或速度慢的问题。解决方法是下载离线包。然后需要进行以下步骤:
- 找到nltk包的data可以解析的路径:
print(nltk.data.path)
- 将离线包中packages目录重命名为nltk_data,并放入一个可解析的路径中,将子目录下的压缩包解压
- 或者通过下面的命令添加自己的路径,但是每次使用nltk时都需要运行下面的命令
nltk.data.path.append('nltk_data的存放路径')
- 检测是否成功
from nltk.book import *
1.2 搜索文本
#查找单词
text1.concordance('monstrous')
#查找和目标单词有着相似上下文的单词
text1.similar('monstrous')
#查找多个单词的共同的上下文
text2.common_contexts(['monstrous', 'very'])
#多个单词位置信息离散图
text4.dispersion_plot(['citizens', 'democracy'])
1.3 词汇计数
print(len(text1))
#统计不重复字符并进行排序
a = sorted(set(text1))
#单词计数
print(text1.count('monstrous'))
3. Computing with Language: Simple Statistics
3.1 频率分布
fdist1 = FreqDist(text1) #计算单词出现次数
print(fdist1.most_common(50))#出现次数最高的前50个单词及其出现次数
print(fdist1['whale'])#单词出现次数
print(fdist1.N())#样本长度
print(fdist1.freq('whale'))#单词出现频率
fdist1.plot(50, cumulative=True)#频率排名前50的词的累积频率图
print(fdist1.hapaxes()) #只出现一次的低频词
print(text4.collocation_list())#双连词
print(fdist1.max())#出现次数最多的单词