Jupyter Notebook nbconvert无需魔术命令/无降价促销

发布于 2021-01-29 16:44:15

我有一个Jupyter笔记本,我想将其转换成一个Python使用脚本nbconvert命令从 Jupyter笔记本电脑。

我在笔记本末尾添加了以下行:

!jupyter nbconvert --to script <filename>.ipynb

这将创建一个Python脚本。但是,我希望生成的.py文件具有以下属性:

  1. 没有输入语句,例如:

#In [27]:

  1. 没有降价,包括如下语句:

#编码:utf-8

  1. 忽略以下%magic命令:

    1. %matplotlib inline
    2. !jupyter nbconvert --to script <filename>.ipynb,即笔记本中执行Python转换的命令

当前,%magic命令已转换为以下形式:get_ipython().magic(...),但不一定在中识别Python

关注者
0
被浏览
48
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    一种控制输出内容的方法是标记不需要的单元格,然后使用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"
    

    要删除注释行和输入语句市场(如#[1]),我相信您需要在调用!jupyter nbconvert
    from的单元格之后,对单元格中的以下内容进行如下处理:这是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())
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看