将 jupyter 实验室笔记本转换为脚本,无需在单元格之间添加注释和新行

cpa*_*age 4 python jupyter-notebook

如何在转换时将jupyter lab笔记本转换为*.py不添加任何空行和注释的脚本(例如# In[103]:)?我目前可以使用 进行转换jupyter nbconvert --to script 'test.ipynb',但这会在笔记本单元格之间添加空行和注释。

kHa*_*hit 5

截至目前,jupyter 默认不提供此类功能。不过,您可以使用几行代码从 python 文件中手动删除空行和注释,例如

def process(filename):
    """Removes empty lines and lines that contain only whitespace, and
    lines with comments"""

    with open(filename) as in_file, open(filename, 'r+') as out_file:
        for line in in_file:
            if not line.strip().startswith("#") and not line.isspace():
                out_file.writelines(line)
Run Code Online (Sandbox Code Playgroud)

现在,只需在从 jupyter notebook 转换的 python 文件上调用此函数。

process('test.py')
Run Code Online (Sandbox Code Playgroud)

另外,如果你想有一个单一的效用函数jupyter笔记本Python文件,不具有注释和空行转换,您可以在以下功能建议上面的代码在这里

import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, out_file):
    with open(notebookPath) as fh:
        nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)

    exporter = PythonExporter()
    source, meta = exporter.from_notebook_node(nb)

    with open(out_file, 'w+') as out_file:
        out_file.writelines(source)

    # include above `process` code here with proper modification
Run Code Online (Sandbox Code Playgroud)