【问题标题】:How do I format this dictionary in python?如何在 python 中格式化这个字典?
【发布时间】:2021-05-30 19:19:03
【问题描述】:

我正在制作一个聊天机器人来检测毒性,使用谷歌透视 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 以获得第一个 "value": 0.05588363 作为字符串或 int? 非常感谢您的帮助!

这是我的代码:

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(my_dict["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"])?您应该可以将int() 替换为str()

标签: python json api dictionary format


【解决方案1】:

那将是类似的东西 dict["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"].

【讨论】:

  • 我试过了,我会改变我的问题以显示我的代码,但它出现了错误。
  • 我收到此错误:Traceback (most recent call last): File "main.py", line 21, in <module> final = int(val["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]) TypeError: string indices must be integers
  • 哦等等,我只需要更好地处理结果
  • 我是否正确地说,我需要将结果值转换为接受小数的格式?
  • 您的结果是一个字符串,因为您调用了json.dumps()。要将 JSON 字符串读取为字典,您可以使用 json.loads (stackoverflow.com/questions/45148704/…)
【解决方案2】:

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

它将所有 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)

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多