name: jupyter description: 以编程方式读取、修改、执行和转换Jupyter笔记本。在处理.ipynb文件进行数据科学工作流时使用,包括编辑单元格、清除输出或转换为其他格式。 triggers:
- ipynb
- jupyter
Jupyter Notebook 指南
笔记本是JSON文件。单元格在 nb['cells'] 中,每个有 source(字符串列表)和 cell_type(‘code’、‘markdown’ 或 ‘raw’)。
修改笔记本
import json
with open('notebook.ipynb') as f:
nb = json.load(f)
# 修改 nb['cells'][i]['source'],然后:
with open('notebook.ipynb', 'w') as f:
json.dump(nb, f, indent=1)
执行与转换
jupyter nbconvert --to notebook --execute --inplace notebook.ipynb # 原地执行
jupyter nbconvert --to html notebook.ipynb # 转换为HTML
jupyter nbconvert --to script notebook.ipynb # 转换为Python
jupyter nbconvert --to markdown notebook.ipynb # 转换为Markdown
查找代码
grep -n "search_term" notebook.ipynb
单元格结构
# 代码单元格
{"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": ["code
"]}
# Markdown单元格
{"cell_type": "markdown", "metadata": {}, "source": ["# Title
"]}
清除输出
for cell in nb['cells']:
if cell['cell_type'] == 'code':
cell['outputs'] = []
cell['execution_count'] = None