nltk.download()报错手动下载+from nltk.book import *介绍

NLTK

NLTK 大概是最知名的Python自然语言处理工具了,在NLP领域中,最常使用的一个Python库。全称"Natural Language Toolkit", 诞生于宾夕法尼亚大学,以研究和教学为目的而生,因此也特别适合入门学习。
NLTK是一个开源的项目,包含:Python模块,数据集和教程,用于NLP的研究和开发。NLTK包括图形演示和示例数据。其提供的教程解释了工具包支持的语言处理任务背后的基本概念。

nltk.download()报错

安装好nltk之后,下载:

import nltk
nltk.download()

在这里插入图片描述
nltk.download()运行报错问题: [WinError 10054]远程主机强迫关闭了一个现有连接

解决方法:手动下载

首先手动下载nltk数据集(所有的)https://pan.baidu.com/s/1oUsf-FgVAZnQAtZWRwiK4w 提取码:9sor
然后把下载好的压缩包解压至上图中的Download Directory目录下,即G:\ruanjian\anaconda\anaconda3.7\share\目录下,每个人的机子这个地方可能不一样。

安装成功

输入from nltk.book import *,出现以下结果则说明安装成功:
在这里插入图片描述

from nltk.book import *介绍

nltk.text.Text

from nltk.book import * 

type(text1)
dir(text1)
text1.concordance("affection")
text1.similar("monstrous")

类型:
在这里插入图片描述
在这里插入图片描述
Text.concordance(word)
查找某个词并显示一些上下文

Text.similar(word)
搜索与某个词具有相似上下文的单词

Text.common_contexts([word1, word2, …])
搜索参数中所有word相同的上下文,即word1、word2 …相同的上下文
在这里插入图片描述
Text.dispersion_plot([word1, word2, …])
用离散图表示预料中各个word出现的位置序列表示

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

在这里插入图片描述

nltk.probability.FreqDist

自动识别语料库中词汇的频率分布

fdist=FreqDist(samples)
创建包含给定样本的频率分布(samples可以是nltk.text.Text、空格分割的字符串、列表或者其他)

fdist.inc(sample)
增加样本

fdist[word]
word在样本中出现的次数

fdist.freq(word)
word在样本中出现的频率

fdist.N()
样本总数

fdist.keys()
样本list

for sample in fdist:
以频率递减顺序遍历样本

fdist.max()
数值最大样本

fdist.plot()
绘制频率分布图

fdist.plot(cumulative=True)
绘制累积频率分布图

fdist = FreqDist(text1)
fdist.plot(50, cumulative=True)

在这里插入图片描述

nltk.util.bigrams

词语搭配是指经常一起出现的词序列,为了获取搭配首先需要从文本中提取双连词,使用bigrams就可以实现这个功能

list(bigrams(["more", "is", "said", "than", "done"]))

在这里插入图片描述
除了一些含生僻词的情况,英语文本中的词语搭配基本上是频繁出现的双连词。nltk.text.Text中提供了collocations(self, num=20, window_size=2)方法可以直接从Text文本中提取常出现的词语搭配,如下

>>> text4.collocations()
United States; fellow citizens; four years; years ago; Federal
Government; General Government; American people; Vice President; Old
World; Almighty God; Fellow citizens; Chief Magistrate; Chief Justice;
God bless; every citizen; Indian tribes; public debt; one another;
foreign nations; political parties

猜你喜欢

转载自blog.csdn.net/qq_42871249/article/details/105322130