使用NLP库textblob进行情感分析-红楼梦评论

最近做了一个分析国外读者对红楼梦评价的小项目。这部分是使用textblob库对评论进行情感分析,得到情感值,并且进行分类,生成词云。
生成直方图、条形图的数据分析过程见我的这篇文章

读入的数据是这样的格式。包含两行,一行评论,一行url来源。
在这里插入图片描述
生成的结果是这样的result.csv文件
在这里插入图片描述
词云图片:
在这里插入图片描述
代码如下

from textblob import TextBlob
from wordcloud import WordCloud
import pandas as pd
import numpy as np
import csv
from os import listdir

def getComments(filename): # 获取评论列表、评论中所有的单词,以空格分隔
    comments = np.zeros(0)
    words = ''
    com_file = pd.read_csv(filename)
    comments = np.append(comments, com_file['comment'])
    for each in comments:
        words += each
    replace_list = [',', '.', '\'', '\"']
    for each in replace_list:
        words = words.replace(each, ' ')
    return comments, words

def getWordCloud(text_str, picture_name): # 生成词云
    wordcloud = WordCloud(background_color="white",width=1980, height=1080, margin=2, random_state=0).generate(text_str)
    wordcloud.to_file(picture_name)

def get_p_or_n(comments): # 获取情绪极化评分,并划定阈值确定是积极、消极或中立
    with open('result.csv', 'w', encoding='utf-8') as csvfile:
        id = 0
        writer = csv.writer(csvfile)
        writer.writerow(['id', 'result', 'score', 'comment'])
        with open('samples.csv', 'w', encoding='utf-8') as samples_file:
            writer_samples = csv.writer(samples_file)
            writer_samples.writerow(['id', 'result', 'score', 'OurJudge', 'comment'])
            for each in comments:
                judge = TextBlob(each)
                # print(each)
                result = ''
                score = judge.sentiment.polarity
                if score > 0.05:
                    result = '积极'
                elif score < -0.03:
                    result = '消极'
                else:
                    result = '中立'
                id += 1
                writer.writerow([id, result, score, each])
                if id%5 == 0:
                    writer_samples.writerow([id, result, score, '', each])

def main():
    filename = "comments.csv"
    comments, words = getComments(filename)
    print(len(comments))
    getWordCloud(words, "WordCloud.png")
    get_p_or_n(comments)

if __name__ == "__main__":
    main()
  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值