Jupyter Notebook nbconvert无需魔术命令/无降价促销 [英] Jupyter Notebook nbconvert without magic commands/ w/o markdown
问题描述
我有一个Jupyter
笔记本,我想使用nbconvert
命令将其转换为Python
脚本.
I have a Jupyter
notebook and I'd like to convert it into a Python
script using the nbconvert
command from within the Jupyter
notebook.
我在笔记本的末尾添加了以下行:
I have included the following line at the end of the notebook:
!jupyter nbconvert --to script <filename>.ipynb
这将创建一个Python
脚本.但是,我希望生成的.py
文件具有以下属性:
This creates a Python
script. However, I'd like the resulting .py
file to have the following properties:
- 没有输入语句,例如:
- No input statements, such as:
#In [27]:
# In[27]:
#编码:utf-8
# coding: utf-8
忽略%magic
命令,例如:
Ignore %magic
commands such as:
-
%matplotlib inline
-
!jupyter nbconvert --to script <filename>.ipynb
,即笔记本中执行Python
转换的命令
%matplotlib inline
!jupyter nbconvert --to script <filename>.ipynb
, i.e. the command within the notebook that executes thePython
conversion
当前,%magic
命令被转换为以下形式:get_ipython().magic(...)
,但是这些不一定在Python
中被识别.
Currently, the %magic
commands get translated to the form: get_ipython().magic(...)
, but these are not necessarily recognized in Python
.
推荐答案
控制输出内容的一种方法是标记输出中不需要的单元格,然后使用TagRemovePreprocessor删除细胞.
One way to get control of what appears in the output is to tag the cells that you don't want in the output and then use the TagRemovePreprocessor to remove the cells.
下面的代码还使用TemplateExporter中的exclude_markdown函数来删除markdown.
The code below also uses the exclude_markdown function in the TemplateExporter to remove markdown.
!jupyter nbconvert \
--TagRemovePreprocessor.enabled=True \
--TagRemovePreprocessor.remove_cell_tags="['parameters']" \
--TemplateExporter.exclude_markdown=True \
--to python "notebook_with_parameters_removed.ipynb"
要删除注释行和输入语句市场(如#[1]),我认为您需要在调用!jupyter nbconvert的单元格中使用以下内容对Python文件进行后处理.来自(请注意,这是Python 3代码):
To remove the commented lines and the input statement markets (like # [1]), I believe you'll need to post-process the Python file with something like the following in the cell after the cell you call !jupyter nbconvert from (note that this is Python 3 code):
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())
这篇关于Jupyter Notebook nbconvert无需魔术命令/无降价促销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!