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



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

截至目前,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 notebook转换为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

只是在这里回答的修改使用命令参数 https://stackoverflow.com/a/54035145/8420173

 #!/usr/bin/env python3
 import sys
 import json
 import argparse
 def main(files):
    for file in files:
        print('#!/usr/bin/env python')
        print('')
        code = json.load(open(file))
        for cell in code['cells']:
            if cell['cell_type'] == 'code':
                for line in cell['source']:
                    if not line.strip().startswith("#") and not line.isspace():
                        print(line, end='')
                print('n')
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('file',nargs='+',help='Path to the file')
    args_namespace = parser.parse_args()
    args = vars(args_namespace)['file']
    main(args)

将以下内容写入文件 MyFile.py,然后

chmod +x MyFile.py

这就是根据您的要求从 IPython 笔记本获取代码的方式。

./MyFile path/to/file/File.ipynb > Final.py

最新更新