【问题标题】:KeyError in Python Code even though Key is present即使存在 Key,Python 代码中的 KeyError
【发布时间】:2020-02-26 18:30:31
【问题描述】:

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

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

【问题讨论】:

  • 使用print(cha)查看密钥"end_time"是否真的存在。也许您在cha 中的价值与您的预期不同。
  • JSON 再见。你没有cha['end_time'],而是cha['items'][0]['end_time'](或cha_item["end_time"],最终是word['end_time']
  • @furas 非常感谢,成功了!它现在再次弹出,但在第 27 行出现以下错误:[ERROR] KeyError: 'end_time' Traceback (most recent call last): File "/var/task/lambda_function.py", line 27, in lambda_handler if word["end_time"] == cha_item["end_time"] and word["start_time"] == cha_item["start_time"]:
  • 你可能有同样的问题 - 你使用没有键 'end_time' 的项目所以使用 print() 检查变量中的值 - 也许我错了,word 没有键end_time。总是在出现错误时使用 print() 检查变量中的值 - 这称为“打印调试”
  • 很有意思,感谢大家的帮助,对以后的开发很有帮助! :)

标签: python json key keyerror


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2014-09-09
    • 2019-12-07
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多