IBM Watson Tone Analyzer JSON响应解析问题求助
解决IBM Watson Tone Analyzer JSON响应解析问题
看起来你在解析Watson Tone Analyzer的返回结果时卡壳了,我先帮你补全代码里的缺失部分,再一步步教你怎么正确遍历响应里的语气数据。
首先,先把你的代码补全并修正(填充必要的API信息和调用逻辑):
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 # 替换成你自己的API密钥/凭证 musixmatch = Musixmatch('YOUR_MUSIXMATCH_API_KEY') tone_analyzer = ToneAnalyzerV3( username="YOUR_WATSON_USERNAME", password="YOUR_WATSON_PASSWORD", version='2017-09-21' # 这是Tone Analyzer常用的稳定版本号 ) # 示例分析文本,你也可以从Musixmatch获取歌词传入 sample_text = "I've been walking on sunshine all day, but tonight I feel a little blue." # 调用Tone Analyzer API获取分析结果 try: tone_response = tone_analyzer.tone( {'text': sample_text}, content_type='application/json' ) # 先打印原始响应,方便你直观查看JSON结构 print("原始JSON响应结构:") print(json.dumps(tone_response, indent=2)) except Exception as e: print(f"调用API时出错:{e}", file=sys.stderr)
接下来,我们拆解Watson返回的JSON结构,它主要包含两个核心部分:document_tone(整个文本的整体语气)和sentences_tone(逐句语气分析)。下面是具体的遍历解析方法:
1. 遍历文档整体语气
如果你需要获取整个文本的整体情感/语气评分,可以这样处理:
# 解析文档整体语气 if 'document_tone' in tone_response: document_tones = tone_response['document_tone']['tones'] print("\n=== 文档整体语气分析 ===") for tone in document_tones: print(f"语气类型: {tone['tone_name']}, 置信度得分: {tone['score']:.4f}")
2. 遍历逐句语气分析
如果需要对文本中的每个句子单独分析,就遍历sentences_tone字段:
# 解析每个句子的语气 if 'sentences_tone' in tone_response: sentences = tone_response['sentences_tone'] print("\n=== 逐句语气分析 ===") for idx, sentence in enumerate(sentences, 1): print(f"\n句子 {idx}: {sentence['text']}") sentence_tones = sentence['tones'] if sentence_tones: for tone in sentence_tones: print(f" 语气类型: {tone['tone_name']}, 置信度得分: {tone['score']:.4f}") else: print(" 未检测到明确语气")
几个注意点
- 一定要先做字段存在性检查(比如
if 'document_tone' in tone_response),避免短文本或特殊情况出现KeyError - 记得替换代码中的所有占位符(API密钥、Watson凭证)为你自己的有效信息
- 提前安装依赖:
pip install watson-developer-cloud musixmatch
内容的提问来源于stack exchange,提问作者Quinton Jackson
相关产品推荐
相关产品推荐

