即使存在密钥,Python代码中的KeyError

问题描述 投票:0回答:1

我正在尝试创建通道分隔符代码以分隔打印在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

任何想法为什么会出现此错误?

python json key keyerror
1个回答
0
投票

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

for item in cha["items"]:
    print(item["end_time"])
© www.soinside.com 2019 - 2024. All rights reserved.