gpt4 book ai didi

python - 即使存在 Key,Python 代码中也会出现 KeyError

转载 作者:太空宇宙 更新时间:2023-11-03 20:12:25 26 4
gpt4 key购买 nike

我正在尝试创建一个 channel 分隔符代码来分隔在 JSON 文件中打印的转录。

我有以下代码:

import json
import boto3

def lambda_handler(event, context):
if event:
s3 = boto3.client("s3")
s3_object = event["Records"][0]["s3"]
bucket_name = s3_object["bucket"]["name"]
file_name = s3_object["object"]["key"]
file_obj = s3.get_object(Bucket=bucket_name, Key=file_name)
transcript_result = json.loads(file_obj["Body"].read())

segmented_transcript = transcript_result["results"]["channel_labels"]
items = transcript_result["results"]["items"]

channel_text = []
flag = False
channel_json = {}
for no_of_channel in range (segmented_transcript["number_of_channels"]):
for word in items:
for cha in segmented_transcript["channels"]:
if cha["channel_label"] == "ch_"+str(no_of_channel):
end_time = cha["end_time"]
if "start_time" in word:
if cha["items"]:
for cha_item in cha["items"]:
if word["end_time"] == cha_item["end_time"] and word["start_time"] == cha_item["start_time"]:
channel_text.append(word["alternatives"][0]["content"])
flag = True
elif word["type"] == "punctuation":
if flag and channel_text:
temp = channel_text[-1]
temp += word["alternatives"][0]["content"]
channel_text[-1] = temp
flag = False
break

channel_json["ch_"+str(no_of_channel)] = ' '.join(channel_text)
channel_text = []
print(channel_json)
s3.put_object(Bucket="aws-speaker-separation", Key=file_name, Body=json.dumps(channel_json))

return{
'statusCode': 200,
'body': json.dumps('Channel transcript separated successfully!')
}

但是,当我运行它时,我在第 23 行收到错误消息:

[ERROR] KeyError: 'end_time'
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 23, in lambda_handler
end_time = cha["end_time"]

我很困惑为什么会在我的 JSON 代码中发生这个错误,需要阅读的内容如下:

JSON Code Parameters

知道为什么会出现此错误吗?

最佳答案

cha 是一个 channel ,end_time 是 channel 项目中更深的一层。要访问您 channel 的项目,请执行以下操作:

for item in cha["items"]:
print(item["end_time"])

关于python - 即使存在 Key,Python 代码中也会出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com