繁体   English   中英

从 VSCode 导出 Juypter Notebook 时,如何只显示某些单元格输入或 output?

[英]How do I only show certain cells input or output when exporting a Juypter Notebook from VSCode?

当我从 VSCode 导出我的 Juypter Notebook 时,我只希望显示某些单元格和某些单元格输出。 我无法从 Google、StackOverflow 和 ChatGPT 获得有效的答案。

那么当我在VSCode中将.ipynb文件导出到HTML时,如何修改HTML中包含哪些单元格,哪些不包含? 例如,我该怎么做才能只包含下面单元格的输出而不是实际代码?

import pandas as pd 
import seaborn as sns
df = pd.read_csv(file.csv)
sns.histplot(df['Variable 1']

这篇文章似乎表明最好/唯一的选择是标记单元格,然后使用nbconvert删除它们。 这在 VSCode 中似乎效率低下,尤其是与 RStudio 中的简单output = FALSEecho = FALSE相比。

这似乎应该是一个简单而常见的问题,但我没有从 inte.net 得到好的解决方案。 ChatGPT 建议将#hide-in-export包含到我不想要的单元格中,但这没有用我链接的 StackOverflow 帖子建议使用带有TagRemovePreprocessornbconvert并标记我想要的所有单元格,但这看起来很笨拙。 后续问题:如果使用nbconvert标记单元格并在导出时删除它们,那么在 VSCode 中标记单元格的最快方法是什么?

在此处输入图像描述

虽然还是有点麻烦,但是我觉得还是一个可行的方法。 F12打开web后台,删除单元格或output单元格。

在此处输入图像描述

我仍然不知道是否有更简单的方法,但这是我在 ChatGPT、这篇博文和这个 StackOverflow 答案的帮助下所做的。

首先,有一个 function 将单元格标签添加到您要隐藏的特定单元格:

import json
def add_cell_tag(nb_path, tag, cell_indices):
    # Open the .ipynb file
    with open(nb_path, 'r', encoding='utf-8') as f:
        nb = json.load(f)
    # Get the cells from the notebook
    cells = nb['cells']
    # Add the tag to the specified cells
    for index in cell_indices:
        cell = cells[index]
        if 'metadata' not in cell:
            cell['metadata'] = {}
        if 'tags' not in cell['metadata']:
            cell['metadata']['tags'] = []
        cell['metadata']['tags'].append(tag)
    # Save the modified notebook
    with open(nb_path, 'w', encoding='utf-8') as f:
        json.dump(nb, f)

其次,运行 function 并在 HTML 导出中向要隐藏的单元格添加标签(可以是任何字符串):

add_cell_tag(nb_path, 'hide-code', [0, 1, 2])

最后,在终端中使用nbconvert来导出和过滤笔记本:

jupyter nbconvert --to html --TagRemovePreprocessor.remove_cell_tags=hide-code  path/to/notebook.ipynb

制作的单元格被完全删除或只是TagRemovePreprocessor.remove_single_output_tags或只是输入TagRemovePreprocessor.remove_all_outputs_tags TagRemovePreprocessor.remove_input_tags

不确定最后两个之间的区别。 此外,我还有一个帮手 function 来计算笔记本中的单元格,还有一个帮手清除笔记本中的所有标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM