我在 Python 中使用 IBM Watson 語音到文本 API,并將 JSON 回應存盤為嵌套字典。我可以使用訪問單個記錄pprint(data_response['results'][0]['alternatives'][0]['transcript'])但無法列印所有成績單。我需要將整個成績單轉儲到 .csv 中。我一直在使用使用建議我相同的格式生成的理解嘗試另一篇文章中使用print(a["confidence"] for r in data_response["results"] for a in r["alternatives"]),但我一定不能了解發電機的理解是如何作業的。
這是使用漂亮列印的嵌套字典的樣子:
{'result_index': 0,
'results': [{'alternatives': [{'confidence': 0.99, 'transcript': 'hello '}],
'final': True},
{'alternatives': [{'confidence': 0.9,
'transcript': 'good morning any this is '}],
'final': True},
{'alternatives': [{'confidence': 0.59,
'transcript': "I'm on a recorded morning "
'%HESITATION today start running '
"yeah it's really good how are "
"you %HESITATION it's one three "
'six thank you so much for '
'asking '}],
'final': True},
{'alternatives': [{'confidence': 0.87,
'transcript': 'I appreciate this opportunity '
'to get together with you and '
'%HESITATION you know learn more '
'about you your interest in '}],
'final': True},
編輯:這是我使用來自@SeaChange 的回應將 .pkl 檔案串列轉換為 .csv 檔案的最終解決方案,該回應有助于僅匯出嵌套字典的轉錄部分。我確信有更有效的方法來轉換檔案,但它對我的應用程式非常有用。
# set the input path
input_path = "00_data\Watson Responses"
# set the output path
output_path = "00_data\Watson Scripts"
# set the list of all files in the input path with a file ending of pkl
files = [f for f in glob.glob(input_path "**/*.pkl", recursive=True)]
# open each pkl file, convert the list to a dataframe, and export to a csv
for file in files:
base_name = os.path.basename(file)
f_name, f_ext = os.path.splitext(base_name)
pkl_file = open(join(dirname(__file__), input_path, base_name), 'rb')
data_response = pickle.load(pkl_file)
pkl_file.close()
transcripts = [a["transcript"] for r in data_response["results"] for a in r["alternatives"]]
dataframe = pd.DataFrame(transcripts)
dataframe.to_csv(os.path.join(output_path, f'{f_name}.csv'), index = False, header = False)
uj5u.com熱心網友回復:
transcripts = [a["transcript"] for r in data_response["results"] for a in r["alternatives"]]
這為您提供了所有成績單的串列。那時它只取決于您希望如何格式化輸出檔案。如果您希望每個成績單都在一個新行上,您可以為此使用 writelines。
寫行
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324329.html
標籤:Python json 字典 导出到 csv ibm-屈臣氏
上一篇:如何格式化字典串列中的字典物件?
下一篇:如何在go中編組嵌入式結構?
