You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对查询情感词典获得的多个同结构字典的对应数值进行求和合并

实现方案

修改后的代码实现

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:54:03