Python - Анализ ответа Json от IBM Watson Tone Analyzer - PullRequest
0 голосов
/ 24 апреля 2018

У меня проблема с анализом моего ответа JSON от Tone Analyzer IBM Watson. Я понимаю, что мне нужно войти в словарь, а затем перемещаться по каждому ключу, пока не получу нужную информацию.

Текущий код

from __future__ import print_function
import json
import sys
from os.path import join, dirname
from watson_developer_cloud import ToneAnalyzerV3
from musixmatch import Musixmatch

musixmatch = Musixmatch('')

tone_analyzer = ToneAnalyzerV3(
    username = "",
    password = "",
    version = '',
    url = "https://gateway.watsonplatform.net/tone-analyzer/api" )

lyric = lyricwikia.get_lyrics('Dragonforce', 'Through the fire and flames')



fh = open('lyrics.txt', 'w+')

fh.write(lyric)

fh.close()


f = open('lyrics.txt', 'r+')

print("\ntone_chat() Dragonforce - Through the Fire and Flames:\n")

m = []

for line in f.readlines():

    content_type = 'application/json'
    tone = tone_analyzer.tone({"text": line}, content_type)
    jsonText = json.dumps(tone, indent=2)
    jsonParse = json.loads(jsonText)
    m = jsonParse["document_tone"]["tones"]
    print(m)

f.close()

Я пытаюсь найти способ вернуть несколько результатов из этого JSON Response и сохранить его в словаре в виде пар ключей, но мне трудно разобраться, как это сделать.

Токовый выход

tone_chat () Dragonforce - сквозь огонь и пламя:

[]
[{'score': 0.511165, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.697052, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[]
[{'score': 0.511165, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.697052, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.816009, 'tone_id': 'joy', 'tone_name': 'Joy'}, {'score': 
0.822231, 'tone_id': 'tentative', 'tone_name': 'Tentative'}]
[]
[{'score': 0.518879, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.619897, 'tone_id': 'anger', 'tone_name': 'Anger'}]
[{'score': 0.608597, 'tone_id': 'anger', 'tone_name': 'Anger'}]
[{'score': 0.865077, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.724236, 'tone_id': 'analytical', 'tone_name': 'Analytical'}]
[]
[]
[]
[]
[{'score': 0.557844, 'tone_id': 'joy', 'tone_name': 'Joy'}, {'score': 
0.898327, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[]
[{'score': 0.695561, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.895415, 'tone_id': 'analytical', 'tone_name': 'Analytical'}]
[{'score': 0.616244, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.898327, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.859366, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[]
[]
[{'score': 0.621329, 'tone_id': 'joy', 'tone_name': 'Joy'}]
[{'score': 0.743111, 'tone_id': 'joy', 'tone_name': 'Joy'}]
[]
[{'score': 0.612119, 'tone_id': 'joy', 'tone_name': 'Joy'}]
[]
[{'score': 0.524931, 'tone_id': 'joy', 'tone_name': 'Joy'}, {'score': 
0.786991, 'tone_id': 'tentative', 'tone_name': 'Tentative'}]
[{'score': 0.92125, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[]
[{'score': 0.8152, 'tone_id': 'analytical', 'tone_name': 'Analytical'}, 
{'score': 0.618451, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.638092, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.874372, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.707601, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.687768, 'tone_id': 'analytical', 'tone_name': 'Analytical'}, 
{'score': 0.618451, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.704642, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[]
[{'score': 0.695561, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.895415, 'tone_id': 'analytical', 'tone_name': 'Analytical'}]
[{'score': 0.616244, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.898327, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.859366, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[]
[]
[{'score': 0.516628, 'tone_id': 'fear', 'tone_name': 'Fear'}]
[{'score': 0.524235, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.52202, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, {'score': 
0.786991, 'tone_id': 'tentative', 'tone_name': 'Tentative'}]
[{'score': 0.961633, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[]
[{'score': 0.695561, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.895415, 'tone_id': 'analytical', 'tone_name': 'Analytical'}]
[{'score': 0.616244, 'tone_id': 'sadness', 'tone_name': 'Sadness'}, 
{'score': 0.898327, 'tone_id': 'confident', 'tone_name': 'Confident'}]
[{'score': 0.859366, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[][{'score': 0.816009, 'tone_id': 'joy', 'tone_name': 'Joy'}, {'score': 
0.822231, 'tone_id': 'tentative', 'tone_name': 'Tentative'}]
[]
[{'score': 0.518879, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[]
[{'score': 0.511165, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.697052, 'tone_id': 'sadness', 'tone_name': 'Sadness'}]
[{'score': 0.816009, 'tone_id': 'joy', 'tone_name': 'Joy'}, {'score': 
0.822231, 'tone_id': 'tentative', 'tone_name': 'Tentative'}]
[]

Я создал словарь под названием «эмоции», в который я пытался сохранить эти 2 значения, но он не работал, поэтому я попытался, по крайней мере, получить значения для печати. Должен ли я пойти по-другому, чтобы получить название тона и партитуру, сохраненные в словаре в виде пар ключей? Спасибо за любую помощь!

1 Ответ

0 голосов
/ 25 апреля 2018

У вас есть опечатка. Также JSON-объект является массивом, поэтому вам нужно указать индекс.

Пример:

for row in jsonText:
    for tones in row['document_tone']['tones']:
        print(' Name: {} . Score: {}'.format(tone['tone_name'], tone['score']))
...