我有一個 api 函式的回傳,它給了我這樣的字典:
{'result_index': 0,
'results': [{'final': True,
'alternatives': [{'transcript': "tickets are available ",
'confidence': 0.49}]},
{'final': True,
'alternatives': [{'transcript': 'everything in the mail ',
'confidence': 0.61}]},
{'final': True,
'alternatives': [{'transcript': 'thanks one all ',
'confidence': 0.73}]}]}
可能包含任意數量的成績單,包括 0。如何將所有成績單提取到一個字串中,這樣它會是這樣的:
'tickets are available everything in the mail thanks one all '
uj5u.com熱心網友回復:
假設您只想要第一個替代方案的成績單,以下代碼應該可以作業:
response = {
"result_index": 0,
"results": [
{
"final": True,
"alternatives": [
{"transcript": "tickets are available ", "confidence": 0.49}
],
},
{
"final": True,
"alternatives": [
{"transcript": "everything in the mail ", "confidence": 0.61}
],
},
{
"final": True,
"alternatives": [{"transcript": "thanks one all ", "confidence": 0.73}],
},
],
}
transcripts = ""
for res in response["results"]:
transcripts = res["alternatives"][0]["transcript"]
uj5u.com熱心網友回復:
這適用于所有結果/替代品/成績單。
d = {'result_index': 0,
'results': [{'final': True,
'alternatives': [{'transcript': "tickets are available ",
'confidence': 0.49}]},
{'final': True,
'alternatives': [{'transcript': 'everything in the mail ',
'confidence': 0.61}]},
{'final': True,
'alternatives': [{'transcript': 'thanks one all ',
'confidence': 0.73}]}]}
l = []
for x in d["results"]:
for y in x["alternatives"]:
l.append(y.get("transcript", ""))
print("".join(l))
uj5u.com熱心網友回復:
一種可能的方法是
output = "".join(k.get('transcript', "") for res in response['results'] for k in res.get('alternatives', []))
正如您所說的那樣,在此處使用帶有替代默認值的 get 可能沒有任何內容。假設總是有結果。如果沒有,只需使用 `response.get('results', {})。
uj5u.com熱心網友回復:
應該這樣做,包括尋找缺失的元素:
res = {'result_index': 0,
'results': [
{'final': True,
'alternatives': [
{'transcript': "tickets are available ",
'confidence': 0.49
}
]
},
{'final': True,
'alternatives': [
{'transcript': 'everything in the mail ',
'confidence': 0.61
}
]
},
{'final': True,
'alternatives': [
{'transcript': 'thanks one all ',
'confidence': 0.73
}
]
}
]
}
ts = [
alt.get('transcript','')
for r in (res['results'] if res.get('results') else [])
for alt in (r['alternatives'] if r.get('alternatives') else [])
]
print("".join(ts))
輸出:
tickets are available everything in the mail thanks one all
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418714.html
標籤:
