如何对查询情感词典获得的多个同结构字典的对应数值进行求和合并
实现方案
修改后的代码实现
import pandas as pd # 读取JSON情感词典并转换为字典结构 sentimentos = pd.read_json('/content/sample_data/words_sentiment.json') sentiment_dict = sentimentos.to_dict('dict') def get_sentiment(token, words_sentiment): # 初始化情感维度累加字典,所有维度初始值为0 total_sentiment = { 'anger': 0, 'anticipation': 0, 'disgust': 0, 'fear': 0, 'joy': 0, 'negative': 0, 'positive': 0, 'sadness': 0, 'surprise': 0, 'trust': 0 } for word in token: if word in words_sentiment: # 匹配到目标词,累加各情感维度数值 current = words_sentiment[word] for k in total_sentiment: total_sentiment[k] += current[k] print(current) else: print("Sorry. We couldn't find that word.") # 返回最终累加结果 return total_sentiment # 调用函数并输出结果 final_res = get_sentiment(["im", "mad", "as", "hell"], sentiment_dict) print("累加后的总情感值:", final_res)
输出结果
运行上述代码后,函数返回的final_res就是你需要的合并结果:
{'anger': 2, 'anticipation': 0, 'disgust': 2, 'fear': 2, 'joy': 0, 'negative': 2, 'positive': 0, 'sadness': 2, 'surprise': 0, 'trust': 0}
可选优化
如果情感词典的情感维度不固定,不想硬写初始字典的键,可以使用动态初始化的写法,自动适配所有存在的情感维度:
def get_sentiment(token, words_sentiment): total_sentiment = None for word in token: if word in words_sentiment: current = words_sentiment[word] # 首次匹配到有效词时自动初始化累加字典 if not total_sentiment: total_sentiment = {key: 0 for key in current} for key in total_sentiment: total_sentiment[key] += current[key] print(current) else: print("Sorry. We couldn't find that word.") return total_sentiment or {}
内容的提问来源于stack exchange,提问作者izzypt
相关产品推荐
相关产品推荐

