jupyter

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Jupyter Notebook Guide

Jupyter Notebook 指南

Notebooks are JSON files. Cells are in
nb['cells']
, each has
source
(list of strings) and
cell_type
('code', 'markdown', or 'raw').
Notebook 是JSON文件。单元格存储在
nb['cells']
中,每个单元格包含
source
(字符串列表)和
cell_type
(取值为'code'、'markdown'或'raw')。

Modifying Notebooks

修改Notebook

python
import json
with open('notebook.ipynb') as f:
    nb = json.load(f)
python
import json
with open('notebook.ipynb') as f:
    nb = json.load(f)

Modify nb['cells'][i]['source'], then:

Modify nb['cells'][i]['source'], then:

with open('notebook.ipynb', 'w') as f: json.dump(nb, f, indent=1)
undefined
with open('notebook.ipynb', 'w') as f: json.dump(nb, f, indent=1)
undefined

Executing & Converting

执行与转换

bash
jupyter nbconvert --to notebook --execute --inplace notebook.ipynb  # Execute in place
jupyter nbconvert --to html notebook.ipynb      # Convert to HTML
jupyter nbconvert --to script notebook.ipynb    # Convert to Python
jupyter nbconvert --to markdown notebook.ipynb  # Convert to Markdown
bash
jupyter nbconvert --to notebook --execute --inplace notebook.ipynb  # Execute in place
jupyter nbconvert --to html notebook.ipynb      # Convert to HTML
jupyter nbconvert --to script notebook.ipynb    # Convert to Python
jupyter nbconvert --to markdown notebook.ipynb  # Convert to Markdown

Finding Code

查找代码

bash
grep -n "search_term" notebook.ipynb
bash
grep -n "search_term" notebook.ipynb

Cell Structure

单元格结构

python
undefined
python
undefined

Code cell

Code cell

{"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": ["code\n"]}
{"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": ["code\n"]}

Markdown cell

Markdown cell

{"cell_type": "markdown", "metadata": {}, "source": ["# Title\n"]}
undefined
{"cell_type": "markdown", "metadata": {}, "source": ["# Title\n"]}
undefined

Clear Outputs

清除输出

python
for cell in nb['cells']:
    if cell['cell_type'] == 'code':
        cell['outputs'] = []
        cell['execution_count'] = None
python
for cell in nb['cells']:
    if cell['cell_type'] == 'code':
        cell['outputs'] = []
        cell['execution_count'] = None