赞
踩
背景: 需要对新闻,评论做正负面分析
pip install snownlp
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')
训练完模型之后, 会在当前目录下生成 sentiment.marshal.3 文件
错误的示范:
from snownlp import SnowNLP
# 加载情感分析模块
from snownlp import sentiment
text = '大麦多开一个口ok????正在现场俩口闲死 ' # 文本
s = SnowNLP(text)
print( s.sentiments) # 打印正负面属性值
这样是错误的,这样使用的依然是原有的 训练模型,并没有使用新的
正确步骤:
# -*- 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
当初我走了太多的弯路,还一直以为自己是对的,,, 想想都泪流满面
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。