代码之家  ›  专栏  ›  技术社区  ›  cpage

将Jupyter实验室笔记本转换为脚本,而不添加批注和单元格之间的新行

  •  2
  • cpage  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   kHarshit    7 年前

    到目前为止,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)
    

    现在,只需在从jupyter笔记本转换的python文件上调用这个函数。

    process('test.py')
    

    另外,如果您希望一个实用程序函数将jupyter笔记本转换为没有注释和空行的python文件,那么您可以在下面建议的函数中包含上述代码。 here :

    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
    
    推荐文章