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

后端 未结 10 2181
灰色年华
灰色年华 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:34
    1. Go to https://jupyter.org/
    2. click on nbviewer
    3. Enter the location of your file and render it.
    4. Click on view as code (shown as < />)
    0 讨论(0)
  • 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 -

    0 讨论(0)
  • 2020-12-02 12:36

    well first of all you need to install this packege below:

    sudo apt install ipython
    jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
    

    two option is avaliable either --to python or --to=python mine was like this works fine: jupyter nbconvert --to python while.ipynb

    jupyter nbconvert --to python while.ipynb 
    

    [NbConvertApp] Converting notebook while.ipynb to python [NbConvertApp] Writing 758 bytes to while.py

    pip3 install ipython
    

    if it does not work for you try, by pip3.

    pip3 install ipython
    
    0 讨论(0)
  • 2020-12-02 12:40

    Jupytext allows for such a conversion on the command line, and importantly you can go back again from the script to a notebook (even an executed notebook). See here.

    0 讨论(0)
  • 2020-12-02 12:42

    Copy all the (''.ipynb) files in the Desired folder then execute:

    import os    
    
    desired_path = 'C:\\Users\\Docs\\Ipynb Covertor'
    
    os.chdir(desired_path)
    
    list_of_directory = os.listdir(desired_path)
    
    for file in list_of_directory:
            os.system('ipython nbconvert --to script ' + str(file))
    
    0 讨论(0)
  • 2020-12-02 12:43

    One way to do that would be to upload your script on Colab and download it in .py format from File -> Download .py

    0 讨论(0)
提交回复
热议问题