You need to enable JavaScript to run this app. Python格式化Azure Face API返回的Emotion属性时TypeError报错处理
优惠活动
大模型
产品
解决方案
定价
更多

Python格式化Azure Face API返回的Emotion属性时TypeError报错处理

解决Azure人脸API Emotion对象无法下标访问的格式化问题

报错原因

你触发的TypeError: 'Emotion' object is not subscriptable,核心是Azure Python SDK返回的Emotion是强类型实体类,不是Python原生字典。虽然把对象转成字符串时,SDK的默认序列化输出长得和字典完全一样,但它本身不支持方括号下标的取值操作——所有情绪置信度值都是类的公开属性,必须用点号语法访问。
你之前尝试把情绪名当字典键做下标访问的逻辑,本质是把类实体误判成了字典结构,自然会触发类型错误。

修复实现

不需要逐个硬编码点号访问每个情绪值,可以用内置的getattr方法,通过字符串形式的情绪名动态读取类的属性值,刚好匹配你之前写的遍历情绪列表的逻辑:

  • 定义和期望输出顺序一致的情绪名列表
  • 遍历列表时用getattr(情绪对象, 情绪名)拿到对应置信度浮点数
  • 把0~1区间的浮点数乘以100取整,转成百分比格式
  • 用逗号拼接所有情绪片段,去掉多余的分隔符

核心代码片段

# 按目标输出顺序排列情绪名
emotion_list = ["anger", "contempt", "disgust", "fear", "happiness", "neutral", "sadness", "surprise"]
emotion_entity = face.face_attributes.emotion
format_parts = []
for emo in emotion_list:
    # 动态读取Emotion类上对应属性的置信度值
    score = round(getattr(emotion_entity, emo) * 100)
    format_parts.append(f"{score}% {emo}")
final_emotion_text = ", ".join(format_parts)

完整可运行的适配代码

for image in url_images:
    detected_faces = face_client.face.detect_with_url(url=image, return_face_attributes=face_attributes)
    if not detected_faces:
        await ctx.send('No faces detected in this image')

    for face in detected_faces:
        age = str(face.face_attributes.age)
        age_fin = age.split(".")
        
        gender = str(face.face_attributes.gender)
        gender_fin = gender.split(".")

        # 情绪属性格式化逻辑
        emotion_list = ["anger", "contempt", "disgust", "fear", "happiness", "neutral", "sadness", "surprise"]
        emotion_entity = face.face_attributes.emotion
        format_parts = []
        for emo in emotion_list:
            score = round(getattr(emotion_entity, emo) * 100)
            format_parts.append(f"{score}% {emo}")
        final_emotion_text = ", ".join(format_parts)

        await ctx.send('Facial attributes detected:\nAge: '+ age_fin[0] + 
        '\nGender: ' + gender_fin[1] + 
        '\nEmotion: ' + final_emotion_text)

输出验证

以你之前的实际返回值为例(anger=0.001、contempt=0.002、happiness=0.542、neutral=0.455,其余情绪值为0),最终输出结果为:

Facial attributes detected:
Gender: male
Emotion: 0% anger, 0% contempt, 0% disgust, 0% fear, 54% happiness, 46% neutral, 0% sadness, 0% surprise

补充兼容方案:如果使用的SDK版本支持实体序列化,也可以调用emotion_entity.serialize()把对象转成原生Python字典,之后就可以正常用方括号下标访问值,注意过滤掉结果里默认带的additional_properties空字段即可。如果需要匹配示例里近似整十百分比的展示效果,只要把取整逻辑调整为按10的倍数近似即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 23:15:03