如何将IBM Tone Analyzer输出结果存入Pandas数据框
IBM Tone Analyzer 结果存入Pandas DataFrame 实现方案
核心问题说明
现有代码仅将API返回的嵌套字典结构存入普通列表,直接转DataFrame会得到多层嵌套的字段,不便于后续分析,需要先对返回结构做展平解析,再和原始数据集按行顺序合并。
API返回的嵌套结构存在两个需要兼容的边界情况:
- 短文本可能触发
tones返回空列表 - 单条文本可能识别出多个不同语气,需要兼容多tone存储
第一步:编写结构化解析逻辑
首先编写单条结果的解析函数,提取可直接存入DataFrame的扁平字段,避免字典Key不存在触发报错:
def parse_tone_result(tone_res): # 安全提取tones列表 tones_list = tone_res.get("document_tone", {}).get("tones", []) # 处理空tone的异常情况 if not tones_list: return { "top_tone_score": None, "top_tone_id": None, "top_tone_name": None, "all_tones_score": {} } # 按分数从高到低排序,提取最高置信度的top tone sorted_tones = sorted(tones_list, key=lambda x: x["score"], reverse=True) top_tone = sorted_tones[0] # 存储所有识别到的tone的分数映射,方便后续展开 all_tones_map = {tone["tone_id"]: tone["score"] for tone in tones_list} return { "top_tone_score": top_tone["score"], "top_tone_id": top_tone["tone_id"], "top_tone_name": top_tone["tone_name"], "all_tones_score": all_tones_map }
第二步:改造API调用循环,存储解析后的结果
在原有循环逻辑基础上增加空文本跳过、异常捕获、解析逻辑,避免单次报错中断整个任务:
import time import pandas as pd parsed_results = [] for row_idx, text_content in new_df["description"].items(): # 跳过空文本、非字符串内容,避免无效API调用 if not isinstance(text_content, str) or not text_content.strip(): parsed_results.append({ "top_tone_score": None, "top_tone_id": None, "top_tone_name": None, "all_tones_score": {} }) continue try: # 调用IBM Tone Analyzer接口 tone_analysis = ta.tone( {"text": text_content}, content_type="application/json" # 补充请求类型参数,避免接口校验报错 ).get_result() # 解析单条分析结果 parsed_res = parse_tone_result(tone_analysis) parsed_results.append(parsed_res) except Exception as e: # 异常场景存入空值,同时打印行号方便排查 print(f"第{row_idx}行文本分析失败:{str(e)}") parsed_results.append({ "top_tone_score": None, "top_tone_id": None, "top_tone_name": None, "all_tones_score": {} }) # 加0.1秒延迟,避免触发API限流 time.sleep(0.1)
第三步:和原始数据集合并为最终DataFrame
因为解析结果的存储顺序和原DataFrame的行顺序完全一致,直接按索引拼接即可:
# 解析结果转独立DataFrame tone_feat_df = pd.DataFrame(parsed_results, index=new_df.index) # 横向合并原数据和tone特征 final_df = pd.concat([new_df, tone_feat_df], axis=1)
可选:将所有tone的分数展开为独立列
如果需要把所有识别到的不同语气单独拆成列,方便统计建模,可执行以下逻辑:
# 将all_tones_score字典展开为独立列,未识别到的tone分数填0 expanded_tones = tone_feat_df["all_tones_score"].apply(pd.Series).fillna(0) # 给列名加前缀,避免和原数据列名重名 expanded_tones = expanded_tones.add_prefix("tone_") # 合并到最终数据集 final_df = pd.concat([final_df, expanded_tones], axis=1)
简易版存储方式(无解析)
如果仅需要留存原始API返回结果,不需要做后续数值分析,可直接将原始返回列表转成DataFrame合并:
raw_tone_df = pd.DataFrame(result, index=new_df.index) final_df_simple = pd.concat([new_df, raw_tone_df], axis=1)
注意:这种方式的字段是嵌套字典结构,后续要提取分数需要手动逐层解析,仅适合需要留存原始接口返回的场景,不适合直接做数据分析。
内容的提问来源于stack exchange,提问作者Akhter
相关产品推荐
相关产品推荐

