繁体   English   中英

如何在 python 中格式化此字典?

[英]How do I format this dictionary in python?

我正在制作一个聊天机器人来检测毒性,使用谷歌视角 API,它响应如下所示的字典。

{
  "attributeScores": {
    "TOXICITY": {
      "spanScores": [
        {
          "begin": 0,
          "end": 11,
          "score": {
            "value": 0.05588363,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.05588363,
        "type": "PROBABILITY"
      }
    }
  },
  "languages": [
    "en"
  ],
  "detectedLanguages": [
    "en"
  ]
}

如何格式化上述 json 以获得第一个“值”:0.05588363作为字符串或整数? 帮助将不胜感激!

这是我的代码:

from googleapiclient import discovery
import json
import os

API_KEY= os.getenv('API_KEY')


service = discovery.build('commentanalyzer', 'v1alpha1', developerKey=API_KEY)

analyze_request = {
  'comment': { 'text': 'sample text' },
  'requestedAttributes': {'TOXICITY': {}}
}

response = service.comments().analyze(body=analyze_request).execute()

val = (json.dumps(response, indent=2))


print(val)
final = val["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]

print(final)

对于您的问题,也许是一个更通用的解决方案,而不是使用带有“硬编码”值和枚举的脚本:

它将所有 int/float 值转换为字符串,但是很容易修改它以仅转换特定键的值:

def handler(data):
    if data is not None:
        res = {}
        for k,v in data.items():
            if type(v) not in (dict, list):
                res[k] = str(v) if type(v) in (int, float) else v
            elif type(v) == list:
                t_list = []
                for rec in v:
                    if type(rec) in (dict, list):
                        tmp_l = [{k2:v2} for k2, v2 in handler(rec).items()]
                        t_list.append(tmp_l)
                    else: t_list.append(rec)
                res[k] = t_list[0]
            else: res[k] = handler(v)
        return res
    else: return None

results = handler(data)
print(results)

这将类似于dict["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]

我将您的字典定义为字典:

d = dict({
  "attributeScores": {
    "TOXICITY": {
      "spanScores": [
        {
          "begin": 0,
          "end": 11,
          "score": {
            "value": 0.05588363,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.05588363,
        "type": "PROBABILITY"
      }
    }
  },
  "languages": [
    "en"
  ],
  "detectedLanguages": [
    "en"
  ]
})

然后通过键访问值:

d['attributeScores']['TOXICITY']['summaryScore']['value']
>>0.05588363

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM