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

如何使用Python从DataFrame生成自定义文本分析情感词典?

Python构建自定义情感词典实现方案

下面给出两种常用实现方案,可根据你的数据集规模选择:


前置准备

先把你的标注数据读取为Pandas DataFrame,示例数据读取代码参考:

import pandas as pd

# 读取标注文件,sep根据你实际的分隔符调整,示例为空白分隔
df = pd.read_csv("你的标注文件路径", sep="\s+")

方案1:逐行遍历法(适合小规模数据集,逻辑易懂)

核心逻辑是遍历每一行单词,筛选出取值为1的情感列存入结果:

# 提取所有情感列名(排除单词列'en')
emotion_cols = [col for col in df.columns if col != "en"]
emotion_dict = {}

for _, row in df.iterrows():
    current_word = row["en"]
    # 匹配所有取值为1的情感,转小写匹配示例输出格式
    match_list = [col.lower() for col in emotion_cols if row[col] == 1]
    emotion_dict[current_word] = match_list

方案2:向量化处理法(适合大规模数据集,执行效率更高)

用Pandas内置的向量化操作替代循环,性能提升明显:

# 把单词列设为索引,仅保留情感列数据
emotion_df = df.set_index("en")
# 逐行筛选取值为1的情感列,转小写后输出为字典
emotion_dict = emotion_df.apply(
    lambda x: x[x == 1].index.str.lower().tolist(),
    axis=1
).to_dict()

补充说明

  • 若不需要把情感列名转成小写,删掉代码中的.lower()或.str.lower()即可
  • 若你的情感标注不是0/1二元值,调整判断条件x == 1为你对应的阈值即可

内容的提问来源于stack exchange,提问作者B.Le

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:24:03