赞
踩
import pandas as pd from textblob import TextBlob # 读取已处理的新闻文本 df = pd.read_excel ( 'news_cleaned_tokens.xlsx' ) # 创建一个空的DataFrame来存储情感分析结果 sentiment_df = pd.DataFrame ( columns=['Text', 'Sentiment'] ) # 使用TextBlob进行情感分析 for index, row in df.iterrows ( ): text = row['cleaned_content'] blob = TextBlob ( text ) # 获取情感分数(介于-1和1之间) sentiment_score = blob.sentiment.polarity # 根据情感分数判断情感类别 if sentiment_score > 0: sentiment = 'Positive' elif sentiment_score < 0: sentiment = 'Negative' else: sentiment = 'Neutral' # 将结果添加到DataFrame中 sentiment_df = pd.concat ( [sentiment_df, pd.DataFrame ( {'Text': [text], 'Sentiment': [sentiment]} )], ignore_index=True ) # 保存情感分析结果到Excel文件 sentiment_df.to_excel ( 'sentiment_analysis_results.xlsx', index=False ) print ( "情感分析完成,并已保存结果到 sentiment_analysis_results.xlsx" )
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。