利用实验1完成的分词和去除停用词后的实验文本,进行文本的情感分析。
选择基于(1)情绪词典;或者(2)基于机器训练的两种方式之一,完成逐句的情感标注。
使用情绪词典构建每日情绪指数,可参考以下两种算法:(1)逐句计算每个句子的极性得分,正极性词加1,负极性词则减1。然后每日累计,并使用总新闻条数进行调整。或者(2)计算每日所有新闻中的正极性词与负极性词数量之比。
import os import re import jieba import codecs import xlrd, xlwt from xlutils.copy import copy from collections import defaultdict2. 打开文件
实验要求构建每日情绪指数,就需要对数据按日期分类。我先将excel表格中数据按日期升序排列,可以看到每日有多条评论。将日期转化为数值格式,小数点之前的数字是年月日转换而成,小数点之后代表发帖小时分钟。舍弃小数点之后的数字,这样time一栏相同的数据即是同一天的评论内容。
新建情绪指数.xls,复制time一列,去除重复项,用于写入每日情绪指数。
data = xlrd.open_workbook('新闻数据.xls')
sheet = data.sheet_by_index(0)
data2 = xlrd.open_workbook('情绪指数.xls')
new_data = copy(data2) # 将xlrd对象拷贝转化为xlwt对象
new_sheet = new_data.get_sheet(0) # 获取转化后工作簿中的第一个表格
3. 创建停用词列表
stopwords = [line.strip() for line in open('中文停用词表.txt',encoding='ANSI').readlines()]
4. 编写函数,检查字符串是否含有中文
def haveChinese(string):
for ch in string:
if u'u4e00' <= ch <= u'u9fff':
return True
7. 编写函数,计算情绪指数
读取正情绪词表和负情绪词表为列表,逐词计算每日的极性得分,若该词为正极性词加1,负极性词则减1,然后把总得分除以当日新闻条数进行调整。
def mood_score(word_list,num):
# 读取正向词文件
positive_list = [line.strip() for line in open('00 知网正情绪词表.txt', encoding='utf-8').readlines()]
# 读取否定词文件
negative_list = [line.strip() for line in open('01 知网负情绪词.txt', encoding='utf-8').readlines()]
# 定义分数
score = 0
# 逐词计算每日极性得分,正极性词加1,负极性词则减1
for word in word_list:
if word in positive_list:
score += 1
elif word in negative_list:
score += -1
# 得到的分数除以总新闻条数num
score = score/num
# 将分类结果返回
return score
6. 分词,去除停用词,计算情绪指数
逐条数据进行分词,去停用词,因为要用分词结果计算情绪指数,所以要将分词结果保存为列表。
if条件句:控制当time值与上一条数据的time值不同时,调用mood_score()函数,对当前outstr[]结果进行情绪指数计算并写入表中,然后重新定义一个空数组,开始新一天的分词结果录入;
num变量:用于计数一日内评论条数;
tmp变量:用于计数当前是第几日,便于写入数据。
title = sheet.col_values(3); # 获取第四列内容(标题数据)
content = sheet.col_values(4); # 获取第五列内容(评论正文数据)
time = sheet.col_values(5); # 获取第六列内容(时间数据)
outstr = [] # 输出结果为outstr
num = 0 # 计数一日内评论条数(用于使用总新闻条数调整得分)
tmp = 1 # 计数第几日(用于保存数据时写入第tmp行)
for i in range(1,60001):
seg_title = jieba.lcut(title[i]) # 精简模式,返回一个列表类型的结果
seg_content = jieba.lcut(content[i])
# 若为第一条数据或该数据time与上一条相同,则是在同一日内,直接追加分词结果
if i == 1 or time[i] == time[i-1]:
num += 1 # 评论条数+1
for word in seg_title:
# 去除停用词表中内容
if word not in stopwords:
# 去除不包含中文的词
if haveChinese(word):
outstr.append(word)
for word in seg_content:
if word not in stopwords:
# 去除不包含中文的词
if haveChinese(word):
outstr.append(word)
else:
# print(outstr)
# 计算得分
score = mood_score(outstr, num)
print("当日评论条数为{},情绪指数为{}".format(num, score))
# 写入score
new_sheet.write(tmp, 1, score)
tmp += 1 # 天数计数+1
num = 1 # 重新计数一日内评论条数
# 建立新的列表继续下一日评论分词
outstr = []
for word in seg_title:
# 去除停用词表中内容
if word not in stopwords:
# 去除不包含中文的词
if haveChinese(word):
outstr.append(word)
for word in seg_content:
# 去除停用词表中内容
if word not in stopwords:
# 去除不包含中文的词
if haveChinese(word):
outstr.append(word)
new_data.save("score.xls") # 保存工作簿



