Skip to main content
 首页 » 编程设计

python之为什么打开 jupyter notebook 会得到 "' outputs' were unexpected"错误

2024年11月24日11bluestorm

我正在尝试下载此 post 上的代码.

虽然下载似乎成功了,但当我打开笔记本时,出现错误。

Notebook validation failed

An invalid notebook may not function properly. The validation error was:

Notebook validation failed: Additional properties are not allowed ('execution_count', 'outputs' were unexpected):

为什么打开 jupyter notebook 会出现“'outputs' were unexpected”错误?

有没有一种方法可以用来检查笔记本的哪一部分无效?

请您参考如下方法:

Jupyter 笔记本实际上存储为 JSON 文件,因此您只需在文本编辑器中打开它即可。每个单元格都是一个 JSON 对象,它被解码为 Python dict。

出现此错误的原因是 cell_type 是 markdown,这表示这是一个 Markdown 单元格。

由于 Markdown 单元格是呈现而不是执行,因此它们具有 outputs 和 execution_count 键没有意义,这仅适用于代码 单元格。

您或许可以编写一个简单的脚本来检查您的 Jupyter notebook;像这样:

import json 
 
valid_keys = ['cell_type', 'metadata', 'source'] 
filename = ...  # specify filename here 
 
with open(filename) as f: 
    data = json.load(f) 
 
for index, cell in enumerate(data['cells'], 1): 
    if cell['cell_type'] == 'markdown': 
        extra_keys = [key for key in cell.keys() if key not in valid_keys] 
        if extra_keys:     
            print(f'Cell {index} has the following keys which are invalid for a markdown cell: {extra_keys}')