如何用jupyter nbconvert将Jupyter笔记本转HTML时移除Out[x]?
如何在Jupyter nbconvert转HTML时移除Out[x]输出标识
我经常用jupyter nbconvert把长Jupyter笔记本转成HTML格式分享,很多受众都会问起输出区域的Out[x]标识怎么去掉。这里分享几个规范的处理方法,比临时修改HTML更靠谱:
方法一:自定义nbconvert模板
nbconvert的HTML输出完全基于模板控制,我们可以修改模板来移除Out[x]:
- 先找到nbconvert的默认模板目录,执行命令:
在返回的路径下找到jupyter --data-dirnbconvert/templates/html,里面是默认的HTML模板文件。 - 复制你常用的模板(比如
full.tpl)到自定义模板目录,比如~/.jupyter/nbconvert/templates/html/custom.tpl - 打开
custom.tpl,找到输出提示相关的代码段:
直接删除这段代码,或者用{% if output.execution_count %} <div class="prompt output_prompt">Out[{{ output.execution_count }}]:</div> {% endif %}{# ... #}注释掉。 - 转换时指定自定义模板:
jupyter nbconvert --to html --template custom your_notebook.ipynb
方法二:HTML后处理脚本
如果不想改模板,可以用脚本批量清理生成的HTML文件。用Python的BeautifulSoup很容易实现:
from bs4 import BeautifulSoup # 读取生成的HTML文件 with open('your_notebook.html', 'r', encoding='utf-8') as f: soup = BeautifulSoup(f, 'html.parser') # 移除所有带有output_prompt类的元素 for prompt in soup.find_all('div', class_='output_prompt'): prompt.decompose() # 保存清理后的HTML with open('your_notebook_clean.html', 'w', encoding='utf-8') as f: f.write(str(soup))
执行这个脚本后,生成的新HTML就不会有Out[x]标识了。
方法三:自定义nbconvert预处理器
这种方法更灵活,可以在转换前直接修改笔记本的输出元数据,让nbconvert根本不生成Out[x]:
- 新建一个Python文件
remove_out_prompt.py,写入以下代码:from nbconvert.preprocessors import Preprocessor class RemoveOutPromptPreprocessor(Preprocessor): def preprocess_cell(self, cell, resources, index): # 只处理代码单元格的输出 if cell.cell_type == 'code': for output in cell.outputs: # 移除execution_count属性 if hasattr(output, 'execution_count'): output.execution_count = None return cell, resources - 转换时指定这个预处理器:
jupyter nbconvert --to html --pre remove_out_prompt.RemoveOutPromptPreprocessor your_notebook.ipynb
这几种方法都比临时修改HTML更规范,适合长期复用。
内容的提问来源于stack exchange,提问作者Mitchell van Zuylen
相关产品推荐
相关产品推荐

