Python中NLTK安装和使用的完整指南
最编程
2023-12-26 17:53:37
...
前言
之前做实验用到了情感分析,就下载了一下,这篇博客记录使用过程。
下载安装到实战详细步骤
NLTK下载安装
先使用pip install nltk 安装包
然后运行下面两行代码会弹出如图得GUI界面,注意下载位置,然后点击下载全部下载了大概3.5G。
import nltk
nltk.download()!
- 注意点:可能由于网络原因访问github卡顿导致,不能正常弹出GUI进行下载,可以自己去github下载
网址:https://github.com/nltk/nltk_data/tree/gh-pages/packages
下载成功后查看是否可以使用,运行下面代码看看是否可以调用brown中的词库
from nltk.corpus import brown
print(brown.categories()) # 输出brown语料库的类别
print(len(brown.sents())) # 输出brown语料库的句子数量
print(len(brown.words())) # 输出brown语料库的词数量
'''
结果为:
['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies',
'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance',
'science_fiction']
57340
1161192
'''
这时候有可能报错,说在下面文件夹中没有找到nltk_data
把下载好的文件解压在复制到其中一个文件夹位置即可,注意文件名,让后就能正常使用!
实战:运用自己的数据进行操作
一、使用自己的训练集训练和分析
可以看到我的训练集和代码的结构是这样的:pos和neg里面是txt文本
链接:https://pan.baidu.com/s/1GrNg3ziWJGhcQIWBCr2PMg
提取码:1fb8
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
import os
from nltk.corpus import stopwords
import pandas as pd
def extract_features(word_list):
return dict([(word, True) for word in word_list])
#停用词
stop = stopwords.words('english')
stop1 = ['!', ',' ,'.' ,'?' ,'-s' ,'-ly' ,' ', 's','...']
stop = stop1+stop
print(stop)
#读取txt文本
def readtxt(f,path):
data1 = ['microwave']
# 以 utf-8 的编码格式打开指定文件
f = open(path+f, encoding="utf-8")
# 输出读取到的数据
#data = f.read().split()
data = f.read().split()
for i in range(len(data)):
if data[i] not in stop:
data[i] = [data[i]]
data1 = data1+data[i]
# 关闭文件
f.close()
del data1[0]
return data1
if __name__ == '__main__':
# 加载积极与消极评论 这些评论去掉了一些停用词,是在readtxt韩硕里处理的,
#停用词如 i am you a this 等等在评论中是非常常见的,有可能对结果有影响,应该事先去除
positive_fileids = os.listdir('pos') # 积极 list类型 42条数据 每一条是一个txt文件
print(type(positive_fileids), len(positive_fileids)) # list类型 42条数据 每一条是一个txt文件
negative_fileids = os.listdir('neg')#消极 list类型 22条数据 每一条是一个txt文件自己找的一些数据
print(type(negative_fileids),len(negative_fileids))
# 将这些评论数据分成积极评论和消极评论
# movie_reviews.words(fileids=[f])表示每一个txt文本里面的内容,结果是单词的列表:['films', 'adapted', 'from', 'comic', 'books', 'have', ...]
# features_positive 结果为一个list
# 结果形如:[({'shakesp: True, 'limit': True, 'mouth': True, ..., 'such': True, 'prophetic': True}, 'Positive'), ..., ({...}, 'Positive'), ...]
path = 'pos/'
features_positive = [(extract_features(readtxt(f,path=path)), 'Positive') for f in positive_fileids]
path = 'neg/'
features_negative = [(extract_features(readtxt(f,path=path)), 'Negative') for f in negative_fileids]
# 分成训练数据集(80%)和测试数据集(20%)
threshold_factor = 0.8
threshold_positive = int(threshold_factor * len(features_positive)) # 800
threshold_negative = int(threshold_factor * len(features_negative)) # 800
# 提取特征 800个积极文本800个消极文本构成训练集 200+200构成测试文本
features_train = features_positive[:threshold_positive] + features_negative[:threshold_negative]
features_test = features_positive[threshold_positive:] + features_negative[threshold_negative:]
print("\n训练数据点的数量:", len(features_train))
print("测试数据点的数量:", len(features_test))
# 训练朴素贝叶斯分类器
classifier = NaiveBayesClassifier.train(features_train)
print("\n分类器的准确性:", nltk.classify.util.accuracy(classifier, features_test))
print("\n五大信息最丰富的单词:")
for item in classifier.most_informative_features()[:5]:
print(item[0])
# 输入一些简单的评论
input_reviews = [
"works well with proper preparation.",
]
#运行分类器,获得预测结果
print("\n预测:")
for review in input_reviews:
print("\n评论:", review)
probdist = classifier.prob_classify(extract_features(review.split()))
pred_sentiment = probdist.max()
# 打印输出
print("预测情绪:", pred_sentiment)
print("可能性:", round(probdist.prob(pred_sentiment), 2))
print("结束")
运行结果:这里的准确性有点高,这是因为我选取的一些数据是非常明显的表达积极和消极的所以处理结果比较难以相信
<class 'list'> 42
<class 'list'> 22
训练数据点的数量: 50
测试数据点的数量: 14
分类器的准确性: 1.0
五大信息最丰富的单词:
microwave
product
works
ever
service
预测:
评论: works well with proper preparation.
预测情绪: Positive
可能性: 0.77
结束
二、使用自带库分析
import pandas as pd
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# 分析句子的情感:情感分析是NLP最受欢迎的应用之一。情感分析是指确定一段给定的文本是积极还是消极的过程。
# 有一些场景中,我们还会将“中性“作为第三个选项。情感分析常用于发现人们对于一个特定主题的看法。
# 定义一个用于提取特征的函数
# 输入一段文本返回形如:{'It': True, 'movie': True, 'amazing': True, 'is': True, 'an': True}
# 返回类型是一个dict
if __name__ == '__main__':
# 输入一些简单的评论
#data = pd.read_excel('data3/microwave1.xlsx')
name = 'hair_dryer1'
data = pd.read_excel('../data3/'+name+'.xlsx')
input_reviews = data[u'review_body']
input_reviews = input_reviews.tolist()
input_reviews = [
"works well with proper preparation.",
"i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.",
"piece of junk. got two years of use and it died. customer service says too bad. whirlpool dishwasher died a few months ago. whirlpool is dead to me.",
"am very happy with this"
]
#运行分类器,获得预测结果
for sentence in input_reviews:
sid = SentimentIntensityAnalyzer()
ss = sid.polarity_scores(sentence)
print("句子:"+sentence)
for k in sorted(ss):
print('{0}: {1}, '.format(k, ss[k]), end='')
print()
print("结束")
结果:
句子:works well with proper preparation.
compound: 0.2732, neg: 0.0, neu: 0.656, pos: 0.344,
句子:i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.
compound: -0.7096, neg: 0.258, neu: 0.742, pos: 0.0,
句子:piece of junk. got two years of use and it died. customer service says too bad. whirlpool dishwasher died a few months ago. whirlpool is dead to me.
compound: -0.9432, neg: 0.395, neu: 0.605, pos: 0.0,
句子:am very happy with this
compound: 0.6115, neg: 0.0, neu: 0.5, pos: 0.5,
结束
结果解释:
compound就相当于一个综合评价,主要和消极和积极的可能性有关
neg:消极可能性
pos:积极可能性
neu:中性可能性
推荐阅读
-
贪婪算法在 Python、JavaScript、Java、C++ 和 C# 中的多种实现及其在硬币变化、分数骑士、活动选择和使用哈夫曼编码的最小生成树问题中的应用实例
-
使用 Python 中的 unittestreport 生成 HTML 报告、重新运行失败案例、通过电子邮件发送测试报告,并将结果推送到钉钉和微信。
-
安装和使用 python 的 flask
-
好工具推荐系列:MacPorts 在 macOS 中的安装和使用(含 qt4-mac 教程)
-
什么是可用性测试?有效性(Effectiveness)-- 用户完成特定任务和实现特定目标的正确性和完整性程度;效率(Efficiency)-- 用户完成任务的正确性和完整性程度与所用资源(如时间)之比;满意度(Satisfaction)-- 用户在使用产品时的主观满意度和接受程度。 2.如何获得可用性? 可以参考以下原则:Gould、Boies 和 Lewis(1991 年)为以用户为中心的设计定义了 4 个重要原则: 早期以用户为中心:设计者应在设计过程的早期就努力了解用户的需求。 综合设计:设计的所有方面都应同步发展,而不是按顺序进行。使产品的内部设计始终与用户界面的需求保持一致。 早期和持续测试:当今唯一可行的软件测试方法是经验主义方法,即如果实际用户认为设计可行,该设计就是可行的。通过在整个开发过程中引入可用性测试,用户就有机会在产品推出之前对设计提出反馈意见。 迭代设计:大问题往往掩盖了小问题的存在。设计人员和开发人员应在整个测试过程中对设计进行迭代。 3...什么是可用性测试? 可用性测试是根据可用性标准对图形用户界面进行的系统评估。 可用性测试是衡量用户与系统(网站、软件应用程序、移动技术或任何用户操作设备)交互时的体验质量。4.如何进行可用性测试? l 实验室实验
-
概率论中的常见分布摘要和 python scipy 库的使用:两点分布、二项分布、几何分布、泊松分布、均匀分布、指数分布和正态分布
-
iCloud 切换区域,中国区保留 appStore(更新)--自 2018 年 2 月 28 日起,中国区 iCloud 由云上贵州管理 苹果公司发布的公告 https://support.apple.com/zh-cn/HT208352 关键词 关键部分 受影响的 iCloud 账户:国家或地区设置为 "中国 "的 Apple ID。 iCloud 包含的服务照片、邮件、通讯录、日历、提醒事项、备忘、书签、钱包、钥匙串、云备份、云驱动器、应用程序数据 新条款和条件: 同意仅出于本协议允许的目的并在中国法律允许的范围内使用服务。 云桂洲在提供服务时应使用合理的技能并尽职尽责,但在适用法律允许的最大范围内,我们不保证或担保您通过本服务存储或访问的任何内容不会意外损坏、崩溃、丢失或根据本协议的条款被删除,如果发生此类损坏、崩溃、丢失或删除,我们不承担任何责任。您应自行负责维护您的信息和数据的适当备份。 Apple 和云上贵州有权访问您存储在服务中的所有数据,包括有权根据适用法律相互之间共享、交换和披露所有用户数据(包括内容)。 本协议的解释、效力和履行应适用*法律。对于因本协议引起的或与本协议有关的任何争议,云桂洲和您同意提交中国国际经济贸易仲裁委员会(CIETAC)根据提交仲裁时有效的法律在北京进行具有约束力的仲裁。 由云桂洲管理,用户选择: 停用; ID 到地区; 受 iCloud(由云桂洲运营)条款和条件约束 首先,我想说说我对数据安全的看法。 当我在朋友圈发布通知时,有些朋友回复说国外的操作并没有多安全,或者国外的安全只是相对于国外而言的等等。首先,我非常感谢这些朋友,这让我反思什么是数据安全。以下观点均属个人观点: 国外的月亮一定比国内圆? 这是一个根深蒂固的问题,只要有人说国外的东西比国内好,就会有人嘲笑崇洋媚外。我觉得我们在某些方面应该向国外学习,比如搜索引擎和版权问题。打开百度搜索 "数据安全",第一行肯定是广告。打开谷歌搜索 "数据安全",第一条就是 "数据安全_百度百科" .....各种版权问题大家都明白,支持正版,但不仅客户一心想找免费破解,就连作者也往往没有保护自己劳动成果或产品的想法。但从另一个层面来说,国内的发展和安全,甩国外几条街。没有说哪里好,哪里不好,辩证地去学习更好。 国外也有别有用心的数据泄露,谈何安全? 从加密解密的角度看,自古以来就没有绝对安全的加密,只有相对安全的做法。苹果的棱镜门、微软的 cpu 漏洞,各种参差不齐的被破解案例 ....是的,这的确是一个很好的论据,但凡事都不能只看一面,当年苹果面对FBI破解手机的要求,几经论证,苹果还是拒绝破解。这点拿到国内,只要上面的文件传达下去,还有企业敢说不吗?还敢说不吗? 关于这次iCloud数据迁移个人看法? 把数据迁移到贵州的云端,相当于把手机的所有数据都存储在贵州的云端服务器上。也许访问数据的速度会快很多,但我会把我的iCloud区放到美国,因为我不想数据存在云上贵州后经常接到莫名其妙的电话或短信,更不想因为乱用国外服务器而被请去喝茶。iCloud一个ID,即从中国账号转到美国区,主要用于数据存在美国服务器上。appStore一个ID,除了注册一个中国ID外,专门用来下载应用用,因为国外ID不支持酷狗和网易云等应用。麻烦的是,用了新的 appStore ID 后,当前的应用还得重新下载安装,因为旧的应用 ID 与新的应用 ID 不兼容,安装不了。最后,iCloud迁移后,国内用户使用美国服务器,估计要 "扶墙 "了。 专业步骤: 首先,进行appleID设置,这是前提条件,否则无法选择转移区域! 取消 appleID 的双重认证 取消家庭共享选项 二、窗口下载并安装 icloud 3.0 版
-
[姿势估计] 实践记录:使用 Dlib 和 mediapipe 进行人脸姿势估计 - 本文重点介绍方法 2):方法 1:基于深度学习的方法:。 基于深度学习的方法:基于深度学习的方法利用深度学习模型,如卷积神经网络(CNN)或递归神经网络(RNN),直接从人脸图像中学习姿势估计。这些方法能够学习更复杂的特征表征,并在大规模数据集上取得优异的性能。方法二:基于二维校准信息估计三维姿态信息(计算机视觉 PnP 问题)。 特征点定位:人脸姿态估计的第一步是通过特征点定位来检测和定位人脸的关键点,如眼睛、鼻子和嘴巴。这些关键点提供了人脸的局部结构信息,可用于后续的姿势估计。 旋转表示:常见的旋转表示方法包括欧拉角和旋转矩阵。欧拉角通过三个旋转角度(通常是俯仰、偏航和滚动)描述头部的旋转姿态。旋转矩阵是一个 3x3 矩阵,表示头部从一个坐标系到另一个坐标系的变换。 三维模型重建:根据特征点的定位结果,三维人脸模型可用于姿势估计。通过将人脸的二维图像映射到三维模型上,可以估算出人脸的旋转和平移信息。这就需要建立人脸的三维模型,然后通过优化方法将模型与特征点对齐,从而获得姿势估计结果。 特征点定位 特征点定位是用于检测人脸关键部位的五官基础部分,还有其他更多的特征点表示方法,大家可以参考我上一篇文章中介绍的特征点检测方案实践:人脸校正二次定位操作来解决人脸校正的问题,客户在检测关键点的代码上略有修改,坐标转换部分客户见上图 def get_face_info(image). img_copy = image.copy image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = face_detection.process(image) # 在图像上绘制人脸检测注释。 image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) box_info, facial = None, None if results.detections: for detection in results. for detection in results.detections: mp_drawing.Drawing.detection = 无 mp_drawing.draw_detection(image, detection) 面部 = detection.location_data.relative_keypoints 返回面部 在上述代码中,返回的数据是五官(6 个关键点的坐标),这是用 mediapipe 库实现的,下面我们可以尝试用另一个库:dlib 来实现。 使用 dlib 使用 Dlib 库在 Python 中实现人脸关键点检测的步骤如下: 确保已安装 Dlib 库,可使用以下命令: pip install dlib 导入必要的库: 加载 Dlib 的人脸检测器和关键点检测器模型: 读取图像并将其灰度化: 使用人脸检测器检测图像中的人脸: 对检测到的人脸进行遍历,并使用关键点检测器检测人脸关键点: 显示绘制了关键点的图像: 以下代码将参数 landmarks_part 添加到要返回的关键点坐标中。
-
使用 Python 和 OCR 进行文档解析的完整代码演示(含代码)
-
紧急模式问题处理 - 图 1 紧急模式 根本原因分析 应急模式提供了尽可能小的环境,即使无法进入应急模式,也可以在其中修复系统。在应急模式下,系统只安装根文件系统供读取,不尝试安装任何其他本地文件系统,不激活网络接口,只启动一些基本服务。 进入应急模式的原因通常是 /etc/fstab 文件中存在错误,导致文件系统挂载失败。 文件系统中存在错误,导致。 约束和限制 本节适用于 Linux 操作系统紧急模式。程序涉及修复文件系统。修复文件系统有丢失数据的风险,因此请先备份数据,然后再执行修复操作。 处理方法 输入根密码,然后进入修复模式。 在应急模式下,根分区以只读模式挂载。要修改根目录中的文件,需要执行以下命令以读写模式重新挂载根分区。# mount -o rw,remount / 请执行以下命令首先检查 fstab 文件是否有误,然后尝试挂载所有未挂载的文件系统。# mount -a 如果挂载点不存在,请创建一个挂载点。 如果不存在此类设备,请注释或删除挂载行。 如果指定了不正确的挂载选项,请将挂载参数更改为正确的参数。 如果没有发生错误,但出现 UNEXPECTED INCONSISTENCY;RUN fsck MANUALLY 消息(通常是由文件系统错误引起的),请跳至第 7 步。 执行以下命令打开 /etc/fstab 以修改相应的错误。# vi /etc/fstab /etc/fstab 文件包含以下字段,以空格分隔:[文件系统] [dir] [type] [options] [dump] [fsck] 表 1 /etc/fstab 参数 说明 参数 说明 [文件系统] 要挂载的分区或存储设备。 文件系统]列建议以 UUID 的形式写入。执行 blkid 命令可查询设备文件系统 UUID。 参考格式如下: # <device> <dir> <type> <options> <dump> <fsck>; UUID=b411dc99-f0a0-4c87-9e05-184977be8539 /home ext4 defaults 0 2 使用 UUID 的好处是,它们与磁盘顺序无关。如果你在 BIOS 中更改了存储设备的顺序,或重新插入了存储设备,或者因为某些 BIOS 可能会随机更改存储设备的顺序,那么使用 UUID 会更有效率。 [文件系统] 文件系统]的挂载位置。 类型 挂载设备或分区的文件系统类型,支持多种不同的文件系统:ext2、ext3、ext4、reiserfs、xfs、jfs、smbfs、iso9660、vfat、ntfs、swap 和 auto。 设置为自动类型后,挂载命令会猜测所使用的文件系统类型,这对 CDROM 和 DVD 等移动设备非常有用。 选项 挂载时要使用的参数,有些参数是特定文件系统特有的。例如,默认值参数使用文件系统的默认挂载参数,ext4 的默认参数为:rw、suid、dev、exec、auto、nouser、async。 有关更多参数,请执行以下命令查看 man 手册:# man mount