我希望解析出从以下代码中获得的json:
import json
from watson_developer_cloud import ToneAnalyzerV3Beta
import urllib.request
import codecs
reader = codecs.getreader("utf-8")
tone_analyzer = ToneAnalyzerV3Beta(
url='https://gateway.watsonplatform.net/tone-analyzer/api',
username='<username>',
password='<password>',
version='2016-02-11')
data=json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2)
print (data)
for cat in data['document_tone']['tone_categories']:
print('Category:', cat['category_name'])
for tone in cat['tones']:
print('-', tone['tone_name'])然后继续出错:字符串索引必须是整数,不知道我把球丢到哪里了,但我真的很感激在这一点上能有任何帮助。
发布于 2016-05-30 22:53:36
json.dumps()将对象转换为字符串。所以,data是一个字符串。因此,您不能使用'document_tone'键对其进行索引(它不是dict)。也许你指的是json.loads()?或者,可能tone_analyzer.tone()已经返回了一个dict,不需要loads()
https://stackoverflow.com/questions/37528517
复制相似问题