正负面分析

背景: 需要对新闻,评论做正负面分析

步骤:

1.安装snownlp

			pip install snownlp

2. 训练或导入模型

  1. 训练
    from snownlp import SnowNLP
    # 加载情感分析模块
    from snownlp import sentiment
    text = '大麦多开一个口ok????正在现场俩口闲死 ​​​​' # 文本
    s = SnowNLP(text)
    
    # todo snownlp常用方法
    print(s.keywords(10))  # 提取 10个关键词  数字代表提取数量
    print('/'.join(s.words)) #分词
    print(s.sentences)  # 断句
    
    # s.sentiments  会对文本进行评分
    
    f1 = open('./pos.txt', 'a+')  # 存放正面  名字也可自定义哦
    f2 = open('./neg.txt', 'a+')  # 存放负面
    if s.sentiments < 0.3:  # 可以自定义范围
    	print('这是一个负面评价')
    	# 这段文本写入neg文件中
    	f2.write(text)
    	f2.write('\n')
    	
    elif s.sentiments > 0.8:  # 可以自定义范围
    	print('这是一个正面评价')
    	# 这段文本写入pos文件中
    	f1.write(text)
    	f1.write('\n')
    else:
    	print('这是一个中性评价')
    	
    # 保存此次的训练模型
    sentiment.train('neg.txt', 'pos.txt')
    # 生成新的训练模型
    sentiment.save('sentiment.marshal')
    
    
  2. 导入
    读取数据,或导入csv文件 (前提是已经做好正负面分析的数据), 安装正负面导入 nrg.txt 和 pos.txt文件,并保存训练模型

训练完模型之后, 会在当前目录下生成 sentiment.marshal.3 文件

3. 加载新的训练模型

错误的示范:

from snownlp import SnowNLP
# 加载情感分析模块
from snownlp import sentiment
text = '大麦多开一个口ok????正在现场俩口闲死 ​​​​' # 文本
s = SnowNLP(text)

print( s.sentiments)  # 打印正负面属性值
 这样是错误的,这样使用的依然是原有的  训练模型,并没有使用新的

正确步骤:

  1. 从引入 from snownlp import sentiment 进入 sentiment文件, 进而修改data_path 方法
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import codecs

from .. import normal
from .. import seg
from ..classification.bayes import Bayes

# 加载原来的数据模型
# data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
#                          'sentiment.marshal')

# 加载本地新训练的模型   本地路径
data_path = 'C:/Users/**/Desktop/python文件/自然语言处理/语言处理/sentiment.marshal'


class Sentiment(object):
	pass
  1. 用新模型判断数据的正负面

当初我走了太多的弯路,还一直以为自己是对的,,, 想想都泪流满面

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐