pro*_*ofj 3 python jupyter-notebook nbconvert
我有一个Jupyter笔记本,我想将其转换成一个Python使用脚本nbconvert命令从内的Jupyter笔记本电脑。
我在笔记本的末尾包含了以下行:
!jupyter nbconvert --to script <filename>.ipynb
Run Code Online (Sandbox Code Playgroud)
这将创建一个Python脚本。但是,我希望生成的.py文件具有以下属性:
# 在[27]:
# 编码:utf-8
忽略%magic命令,例如:
%matplotlib inline!jupyter nbconvert --to script <filename>.ipynb,即笔记本中执行Python转换的命令目前,%magic命令被转换为形式:get_ipython().magic(...),但这些不一定在Python.
控制输出中出现的内容的一种方法是标记输出中不需要的单元格,然后使用 TagRemovePreprocessor 删除这些单元格。
下面的代码还使用了 TemplateExporter 中的 exclude_markdown 函数来删除 markdown。
!jupyter nbconvert \
--TagRemovePreprocessor.enabled=True \
--TagRemovePreprocessor.remove_cell_tags="['parameters']" \
--TemplateExporter.exclude_markdown=True \
--to python "notebook_with_parameters_removed.ipynb"
Run Code Online (Sandbox Code Playgroud)
要删除注释行和输入语句市场(如# [1]),我相信您需要在您调用 !jupyter nbconvert 的单元格之后的单元格中使用以下内容对 Python 文件进行后处理(注意这是 Python 3 代码):
import re
from pathlib import Path
filename = Path.cwd() / 'notebook_with_parameters_removed.py'
code_text = filename.read_text().split('\n')
lines = [line for line in code_text if len(line) == 0 or
(line[0] != '#' and 'get_ipython()' not in line)]
clean_code = '\n'.join(lines)
clean_code = re.sub(r'\n{2,}', '\n\n', clean_code)
filename.write_text(clean_code.strip())
Run Code Online (Sandbox Code Playgroud)