convert json ipython notebook(.ipynb) to .py file

后端 未结 10 2226
灰色年华
灰色年华 2020-12-02 12:28

How do you convert an IPython notebook file (json with .ipynb extension) into a regular .py module?

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 12:35

    You can use the following script to convert jupyter notebook to Python script, or view the code directly.

    To do this, write the following contents into a file cat_ipynb, then chmod +x cat_ipynb.

    #!/usr/bin/env python
    import sys
    import json
    
    for file in sys.argv[1:]:
        print('# file: %s' % file)
        print('# vi: filetype=python')
        print('')
        code = json.load(open(file))
    
        for cell in code['cells']:
            if cell['cell_type'] == 'code':
                print('# -------- code --------')
                for line in cell['source']:
                    print(line, end='')
                print('\n')
            elif cell['cell_type'] == 'markdown':
                print('# -------- markdown --------')
                for line in cell['source']:
                    print("#", line, end='')
                print('\n')
    

    Then you can use

    cat_ipynb your_notebook.ipynb > output.py

    Or show it with vi directly

    cat_ipynb your_notebook.ipynb | view -

提交回复
热议问题