软件工程 推特情感分析

该代码段读取CSV文件中的Twitter数据,使用nltk进行句子和单词分割,进行词性标注,并利用TextBlob进行情感分析。它计算每个句子的情感得分,然后根据得分确定情感态度,最后汇总所有句子的情感得分以得出整体态度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import nltk
from textblob import TextBlob
import pandas as pd
import os
os.chdir("F:\\")
# 读取csv文件
df = pd.read_csv('Twitter.csv')

# 获取第3行和第2列的数据
row_num = 2
col_num = 3
print(df.iloc[row_num])
print(df.iloc[:, col_num])
# 输入英文文本
text = df.iloc[2, 2]
# 分句
sentences = nltk.sent_tokenize(text)

# 分词
words = []
for sentence in sentences:
    words += nltk.word_tokenize(sentence)

# 词性标注
pos_tags = nltk.pos_tag(words)

# 情感分析
sentiment_scores = []
for sentence in sentences:
    blob = TextBlob(sentence)
    sentiment_score = blob.sentiment.polarity
    sentiment_scores.append(sentiment_score)

    # 判断情感态度
    if sentiment_score > 0.5:
        attitude = '非常看好'
    elif sentiment_score <= 0.5 and sentiment_score >= 0.1:
        attitude = '看好'
    elif sentiment_score < 0.1 and sentiment_score > -0.1:
        attitude = '中性'
    elif sentiment_score < -0.1 and sentiment_score >= -0.5:
        attitude = '不太看好'
    else:
        attitude = '非常不看好'

    # 打印结果
    print("Sentence:", sentence)
    print("Sentiment score:", sentiment_score)
    print("Attitude:", attitude)

# 汇总情感得分
total_sentiment_score = sum(sentiment_scores)

# 判断整体情感态度
if total_sentiment_score > 0.5:
    overall_attitude = '非常看好'
elif total_sentiment_score <= 0.5 and total_sentiment_score >= 0.1:
    overall_attitude = '看好'
elif total_sentiment_score < 0.1 and total_sentiment_score > -0.1:
    overall_attitude = '中性'
elif total_sentiment_score < -0.1 and total_sentiment_score >= -0.5:
    overall_attitude = '不太看好'
else:
    overall_attitude = '非常不看好'

# 打印整体情感得分和态度
print("Total sentiment score:", total_sentiment_score)
print("Overall attitude:", overall_attitude)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值