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

Python读取txt生成字典后如何将情感字符串值替换为对应整数

实现方法

你可以通过预先定义情感类别到整数的映射关系完成替换,有两种常用实现思路:

方法1:读取文件时直接转换(推荐)

不需要额外遍历已有字典,读取数据的同时就完成值的转换,效率更高,同时用上下文管理器管理文件避免资源泄漏:

# 定义情感字符串和对应整数的映射
sentiment_map = {
    "negative": -1,
    "neutral": 0,
    "positive": 1
}
dictionary = {}
# with语句会在读取结束后自动关闭文件,不需要手动调用close()
with open('adjective_sentiment.txt', 'r', encoding='utf-8') as infile:
    for line in infile:
        line = line.strip()
        # 跳过文件中的空行
        if not line:
            continue
        adj, sentiment = line.split()
        dictionary[adj] = sentiment_map[sentiment]
# 打印最终结果
print(dictionary)

方法2:对已生成的字符串值字典做替换

如果你已经生成了值为情感字符串的原字典,可以直接遍历修改或者生成新字典:

sentiment_map = {
    "negative": -1,
    "neutral": 0,
    "positive": 1
}
# 方案A:直接修改原字典
for key in dictionary:
    dictionary[key] = sentiment_map[dictionary[key]]

# 方案B:生成新字典,不改动原字典数据
new_dict = {k: sentiment_map[v] for k, v in dictionary.items()}

额外注意

如果你的文本文件中可能存在三类之外的异常情感标签,可以用get方法设置默认值避免报错,比如sentiment_map.get(value, 0)就会把不在映射关系里的标签默认归为中性0。


内容的提问来源于stack exchange,提问作者stef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:15:07