【发布时间】: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