前言

之前做实验用到了情感分析,就下载了一下,这篇博客记录使用过程。

下载安装到实战详细步骤

NLTK下载安装

先使用pip install nltk 安装包

然后运行下面两行代码会弹出如图得GUI界面,注意下载位置,然后点击下载全部下载了大概3.5G。

  1. import nltk
  2. nltk.download()!

下载成功后查看是否可以使用,运行下面代码看看是否可以调用brown中的词库

  1. from nltk.corpus import brown
  2. print(brown.categories()) # 输出brown语料库的类别
  3. print(len(brown.sents())) # 输出brown语料库的句子数量
  4. print(len(brown.words())) # 输出brown语料库的词数量
  5. '''
  6. 结果为:
  7. ['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies',
  8. 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance',
  9. 'science_fiction']
  10. 57340
  11. 1161192
  12. '''

这时候有可能报错,说在下面文件夹中没有找到nltk_data

把下载好的文件解压在复制到其中一个文件夹位置即可,注意文件名,让后就能正常使用!

实战:运用自己的数据进行操作

一、使用自己的训练集训练和分析

可以看到我的训练集和代码的结构是这样的:pos和neg里面是txt文本

链接:https://pan.baidu.com/s/1GrNg3ziWJGhcQIWBCr2PMg

提取码:1fb8

  1. import nltk.classify.util
  2. from nltk.classify import NaiveBayesClassifier
  3. import os
  4. from nltk.corpus import stopwords
  5. import pandas as pd
  6. def extract_features(word_list):
  7. return dict([(word, True) for word in word_list])
  8. #停用词
  9. stop = stopwords.words('english')
  10. stop1 = ['!', ',' ,'.' ,'?' ,'-s' ,'-ly' ,' ', 's','...']
  11. stop = stop1+stop
  12. print(stop)
  13. #读取txt文本
  14. def readtxt(f,path):
  15. data1 = ['microwave']
  16. # 以 utf-8 的编码格式打开指定文件
  17. f = open(path+f, encoding="utf-8")
  18. # 输出读取到的数据
  19. #data = f.read().split()
  20. data = f.read().split()
  21. for i in range(len(data)):
  22. if data[i] not in stop:
  23. data[i] = [data[i]]
  24. data1 = data1+data[i]
  25. # 关闭文件
  26. f.close()
  27. del data1[0]
  28. return data1
  29. if __name__ == '__main__':
  30. # 加载积极与消极评论 这些评论去掉了一些停用词,是在readtxt韩硕里处理的,
  31. #停用词如 i am you a this 等等在评论中是非常常见的,有可能对结果有影响,应该事先去除
  32. positive_fileids = os.listdir('pos') # 积极 list类型 42条数据 每一条是一个txt文件
  33. print(type(positive_fileids), len(positive_fileids)) # list类型 42条数据 每一条是一个txt文件
  34. negative_fileids = os.listdir('neg')#消极 list类型 22条数据 每一条是一个txt文件自己找的一些数据
  35. print(type(negative_fileids),len(negative_fileids))
  36. # 将这些评论数据分成积极评论和消极评论
  37. # movie_reviews.words(fileids=[f])表示每一个txt文本里面的内容,结果是单词的列表:['films', 'adapted', 'from', 'comic', 'books', 'have', ...]
  38. # features_positive 结果为一个list
  39. # 结果形如:[({'shakesp: True, 'limit': True, 'mouth': True, ..., 'such': True, 'prophetic': True}, 'Positive'), ..., ({...}, 'Positive'), ...]
  40. path = 'pos/'
  41. features_positive = [(extract_features(readtxt(f,path=path)), 'Positive') for f in positive_fileids]
  42. path = 'neg/'
  43. features_negative = [(extract_features(readtxt(f,path=path)), 'Negative') for f in negative_fileids]
  44. # 分成训练数据集(80%)和测试数据集(20%)
  45. threshold_factor = 0.8
  46. threshold_positive = int(threshold_factor * len(features_positive)) # 800
  47. threshold_negative = int(threshold_factor * len(features_negative)) # 800
  48. # 提取特征 800个积极文本800个消极文本构成训练集 200+200构成测试文本
  49. features_train = features_positive[:threshold_positive] + features_negative[:threshold_negative]
  50. features_test = features_positive[threshold_positive:] + features_negative[threshold_negative:]
  51. print("\n训练数据点的数量:", len(features_train))
  52. print("测试数据点的数量:", len(features_test))
  53. # 训练朴素贝叶斯分类器
  54. classifier = NaiveBayesClassifier.train(features_train)
  55. print("\n分类器的准确性:", nltk.classify.util.accuracy(classifier, features_test))
  56. print("\n五大信息最丰富的单词:")
  57. for item in classifier.most_informative_features()[:5]:
  58. print(item[0])
  59. # 输入一些简单的评论
  60. input_reviews = [
  61. "works well with proper preparation.",
  62. ]
  63. #运行分类器,获得预测结果
  64. print("\n预测:")
  65. for review in input_reviews:
  66. print("\n评论:", review)
  67. probdist = classifier.prob_classify(extract_features(review.split()))
  68. pred_sentiment = probdist.max()
  69. # 打印输出
  70. print("预测情绪:", pred_sentiment)
  71. print("可能性:", round(probdist.prob(pred_sentiment), 2))
  72. print("结束")

运行结果:这里的准确性有点高,这是因为我选取的一些数据是非常明显的表达积极和消极的所以处理结果比较难以相信

  1. <class 'list'> 42
  2. <class 'list'> 22
  3. 训练数据点的数量: 50
  4. 测试数据点的数量: 14
  5. 分类器的准确性: 1.0
  6. 五大信息最丰富的单词:
  7. microwave
  8. product
  9. works
  10. ever
  11. service
  12. 预测:
  13. 评论: works well with proper preparation.
  14. 预测情绪: Positive
  15. 可能性: 0.77
  16. 结束

二、使用自带库分析

  1. import pandas as pd
  2. from nltk.sentiment.vader import SentimentIntensityAnalyzer
  3. # 分析句子的情感:情感分析是NLP最受欢迎的应用之一。情感分析是指确定一段给定的文本是积极还是消极的过程。
  4. # 有一些场景中,我们还会将“中性“作为第三个选项。情感分析常用于发现人们对于一个特定主题的看法。
  5. # 定义一个用于提取特征的函数
  6. # 输入一段文本返回形如:{'It': True, 'movie': True, 'amazing': True, 'is': True, 'an': True}
  7. # 返回类型是一个dict
  8. if __name__ == '__main__':
  9. # 输入一些简单的评论
  10. #data = pd.read_excel('data3/microwave1.xlsx')
  11. name = 'hair_dryer1'
  12. data = pd.read_excel('../data3/'+name+'.xlsx')
  13. input_reviews = data[u'review_body']
  14. input_reviews = input_reviews.tolist()
  15. input_reviews = [
  16. "works well with proper preparation.",
  17. "i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.",
  18. "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.",
  19. "am very happy with this"
  20. ]
  21. #运行分类器,获得预测结果
  22. for sentence in input_reviews:
  23. sid = SentimentIntensityAnalyzer()
  24. ss = sid.polarity_scores(sentence)
  25. print("句子:"+sentence)
  26. for k in sorted(ss):
  27. print('{0}: {1}, '.format(k, ss[k]), end='')
  28. print()
  29. print("结束")

结果:

  1. 句子:works well with proper preparation.
  2. compound: 0.2732, neg: 0.0, neu: 0.656, pos: 0.344,
  3. 句子:i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.
  4. compound: -0.7096, neg: 0.258, neu: 0.742, pos: 0.0,
  5. 句子: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.
  6. compound: -0.9432, neg: 0.395, neu: 0.605, pos: 0.0,
  7. 句子:am very happy with this
  8. compound: 0.6115, neg: 0.0, neu: 0.5, pos: 0.5,
  9. 结束

结果解释:

compound就相当于一个综合评价,主要和消极和积极的可能性有关

neg:消极可能性

pos:积极可能性

neu:中性可能性

记录NLTK安装使用全过程--python的更多相关文章

  1. Ubuntu14.04 Django Mysql安装部署全过程

    Ubuntu14.04 Django Mysql安装部署全过程   一.简要步骤.(阿里云Ubuntu14.04) Python安装 Django Mysql的安装与配置 记录一下我的部署过程,也方便 ...

  2. Ubuntu 14.04下Django+MySQL安装部署全过程

    一.简要步骤.(Ubuntu14.04) Python安装 Django Mysql的安装与配置 记录一下我的部署过程,也方便一些有需要的童鞋,大神勿喷~ 二.Python的安装 由于博主使用的环境是 ...

  3. 基础知识:编程语言介绍、Python介绍、Python解释器安装、运行Python解释器的两种方式、变量、数据类型基本使用

    2018年3月19日 今日学习内容: 1.编程语言的介绍 2.Python介绍 3.安装Python解释器(多版本共存) 4.运行Python解释器程序两种方式.(交互式与命令行式)(♥♥♥♥♥) 5 ...

  4. LinuxMint上安装redis和python遇到的一些问题

    今天在安装Redis和Python上遇到了些问题,解决后记录下来. 环境:LinuxMint 18.3 安装redis sudo wget http://download.redis.io/relea ...

  5. window 安装gdal和python

    进入 http://www.gisinternals.com/release.php 中下载下图(也可以不是这个版本但是下载的python和gdal一定要版本对应) 1.点击下图中release-17 ...

  6. 【转】Ubuntu 14.04下Django+MySQL安装部署全过程

    一.简要步骤.(阿里云Ubuntu14.04) Python安装 Django Mysql的安装与配置 记录一下我的部署过程,也方便一些有需要的童鞋,大神勿喷~ 二.Python的安装 由于博主使用的 ...

  7. 编程语言、Python介绍及其解释器安装、运行Python解释器的两种方式、变量、内存管理

    一.编程语言介绍 1.1 机器语言:直接用计算机能理解的二进制指令来编写程序,直接控制硬件. 1.2 汇编语言:在机器语言的基础上,用英文标签取代二进制指令来编写程序,本质上也是直接控制硬件. 以上2 ...

  8. 【python】pyenv与virtualenv安装,实现python多版本多项目管理

    踩了很多坑,记录一下这次试验,本次测试环境:Linux centos7 64位. pyenv是一个python版本管理工具,它能够进行全局的python版本切换,也可以为单个项目提供对应的python ...

  9. Windows安装多个python解释器

    Windows安装多个python解释器 ​ 在windows10系统下安装两个不同版本的的python解释器,在通常情况下编译执行文件都是没问题的,但是加载或下载包的时候pip的使用就会出现问题,无 ...

随机推荐

  1. 有个姑娘叫history

    文章目录 常用参数 history的一些用法 修改history命令默认保存的数量 来给history穿衣服 让我们重新认识一下history history命令用于显示用户以前执行过的历史命令,并且 ...

  2. gdb调试小技巧

    1.进入gdb,需要源码,然后gdb+可执行文件,如果要看代码一起的就gdb+可执行文件+tui 2.设置参数 set args +参数 3.设置断点,可以b +行数或者b+函数名字 4.r就是一直跑 ...

  3. Devops 开发运维高级篇之微服务代码上传和代码检查

    Devops 开发运维高级篇之微服务代码上传和代码检查 微服务持续集成(1)-项目代码上传到Gitlab 微服务持续集成(2)-从Gitlab拉取项目源码 微服务持续集成(3)-提交到SonarQub ...

  4. C++ 序列操作函数最全总结

    标准库定义了许多用于操作序列的算法,大多在algorithm和numeric文件中,大多数函数的原理并不复杂,但是在很多情况下可以替代手写的情况,甚至更加优秀. 这类算法函数非常多,但是他们都有共同的 ...

  5. 痞子衡嵌入式:揭秘i.MXRT1170上串行NOR Flash双程序可交替启动设计

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是i.MXRT1170上串行NOR Flash双程序可交替启动设计. 在上一篇文章 <i.MXRT1060/1010上串行NOR F ...

  6. 【测试必备】k8s基本使用(更新中。。。)

    测试为什么要学习容器技术及k8s k8s不是运维的专属技术 随着互联网技术的发展,架构也已经从单体架构发展到容器云( "微服务 + k8s" 完美结合) 很多人认为,k8s只是运维 ...

  7. 2022李宏毅作业hw1—新冠阳性人员数量预测。

    ​ 事前  : kaggle地址:ML2021Spring-hw1 | Kaggle 我的git地址: https://github.com/xiaolilaoli/lihongyi2022homew ...

  8. 如何在Excel里安装excel插件?

    随着科技的发展,人们对数据分析的要求越来越多, Excel也存在一些问题,长期困扰一线业务用户:首先是性能问题.对于大数据量,Excel处理起来很慢.数据获取的过程麻烦,特别是周期性的数据获取,每次都 ...

  9. 多态在C#中的应用

    C# 语言经过专门设计,以便不同库中的基类与派生类之间的版本控制可以不断向前发展,同时保持向后兼容.这具有多方面的意义.例如,这意味着在基类中引入与派生类中的某个成员具有相同名称的新成员在 C# 中是 ...

  10. linux中ctrl+c、ctrl+z、ctrl+d区别

    转至:https://www.cnblogs.com/jintaoblogs/p/11343623.html 一.ctrl-c 发送 SIGINT 信号(程序终止(interrupt)信号)给前台进程 ...