简体   繁体   English

将 JSON IPython 笔记本 (.ipynb) 转换为 .py 文件

[英]Convert JSON IPython notebook (.ipynb) to .py file

How do you convert an IPython notebook file (json with .ipynb extension) into a regular .py module?如何将 IPython 笔记本文件(扩展名为.ipynb的 json)转换为常规.py模块?

From the notebook menu you can save the file directly as a python script.从笔记本菜单中,您可以将文件直接保存为 python 脚本。 Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.转到菜单的“文件”选项,然后选择“下载为”,您会看到一个“Python (.py)”选项。

在此处输入图像描述

Another option would be to use nbconvert from the command line:另一种选择是从命令行使用 nbconvert :

jupyter nbconvert --to script 'my-notebook.ipynb'

Have a look here .看看这里

根据https://ipython.org/ipython-doc/3/notebook/nbconvert.html ,您正在寻找带有 --to 脚本选项的 nbconvert 命令。

ipython nbconvert notebook.ipynb --to script

In short: This command-line option converts mynotebook.ipynb to python code:简而言之:此命令行选项将mynotebook.ipynb转换为python代码:

jupyter nbconvert mynotebook.ipynb --to python

note: this is different from above answer.注意:这与上面的答案不同。 ipython has been renamed to jupyter . ipython已重命名为jupyter the old executable name (ipython) is deprecated.旧的可执行文件名称 (ipython) 已弃用。


More details: jupyter command-line has an nbconvert argument which helps convert notebook files (*.ipynb) to various other formats.更多详细信息: jupyter命令行有一个nbconvert参数,可帮助将笔记本文件(*.ipynb)转换为各种其他格式。

You could even convert it to any one of these formats using the same command but different --to option:您甚至可以使用相同的命令但不同的--to选项将其转换为这些格式中的任何一种:

  • asciidoc asciidoc
  • custom风俗
  • html html
  • latex.乳胶。 (Awesome if you want to paste code in conference/journal papers). (如果您想在会议/期刊论文中粘贴代码,那就太棒了)。
  • markdown降价
  • notebook笔记本
  • pdf pdf
  • python Python
  • rst第一次
  • script脚本
  • slides.幻灯片。 (Whooh! Convert to slides for easy presentation 😊) (哇哦!转换为幻灯片以方便演示😊)

the same command jupyter nbconvert --to latex mynotebook.ipynb相同的命令jupyter nbconvert --to latex mynotebook.ipynb

For more see jupyter nbconvert --help .有关更多信息,请参阅jupyter nbconvert --help There are extensive options to this.这有很多选择。 You could even to execute the code first before converting, different log-level options etc.您甚至可以在转换之前先执行代码,不同的日志级别选项等。

you can use this to do that :你可以用它来做到这一点:

pip install ipynb-py-convert

then run this on your terminal to convert .py file to .ipynb :然后在您的终端上运行它以将 .py 文件转换为 .ipynb :

ipynb-py-convert Ex/abc.py Ex/abc.ipynb

to convert .ipynb files to .py :将 .ipynb 文件转换为 .py :

ipynb-py-convert Ex/abc.ipynb Ex/abc.py

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两个选项可用 --to python 或 --to=python 我的就像这样工作正常: 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 [NbConvertApp] 将笔记本 while.ipynb 转换为 python [NbConvertApp] 将 758 字节写入 while.py

pip3 install ipython

if it does not work for you try, by pip3.如果它不适合你尝试,通过 pip3。

pip3 install ipython

Tested on Ubuntu 20.04Ubuntu 20.04上测试

Install required packages for PIP安装 PIP 所需的软件包

$ pip install ipython
$ pip install nbconvert

To install required packages安装所需的软件包

$ sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-plain-generic

METHOD 1方法一

Use jupyter nbconvert command to convert to different format使用jupyter nbconvert命令转换为不同的格式

Source file pro.ipynb源文件 pro.ipynb

pro.ipynb

  • To convert to ascii转换为ASCII

     $ jupyter nbconvert --to asciidoc pro.ipynb
  • To convert to pdf转换为pdf

     $ jupyter nbconvert --to pdf pro.ipynb
  • To convert to python转换为python

     $ jupyter nbconvert --to python pro.ipynb

METHOD 2方法二

Convert ipynb project through python code use savefig method of pyplot :通过 python 代码转换 ipynb 项目使用pyplotsavefig方法:

pro.ipynb pro.ipynb

import matplotlib.pyplot as plt
%matplotlib inline
exp_vals=[1400,600,300,410,250]
exp_labels=['Home Rent','Food','Phone/Internet Bill','Car','Other Utilities']
plt.axis('equal')
plt.pie(exp_vals,labels=exp_labels,radius=2,autopct='%0.1f%%',shadow=True,explode=[0,0.5,0,0.3,0],startangle=20)
# plt.show()
plt.savefig('piechart.jpg',bbox_inches='tight',pad_inches=2,transparent=True,edgecolor='r')

piechart.png image that it generated:它生成的 piechart.png 图像:

饼图.png

   Hope this helps to convert your ~(`)/\/\/\_ [Python] code

You definitely can achieve that with nbconvert using the following command:您绝对可以使用以下命令通过 nbconvert 实现此目的:

jupyter nbconvert --to python while.ipynb 

However, having used it personally I would advise against it for several reasons:但是,由于个人使用它,我建议不要使用它,原因如下:

  1. It's one thing to be able to convert to simple Python code and another to have all the right abstractions, classes access and methods set up.能够转换为简单的 Python 代码是一回事,而拥有所有正确的抽象、类访问和方法设置是另一回事。 If the whole point of you converting your notebook code to Python is getting to a state where your code and notebooks are maintainable for the long run, then nbconvert alone will not suffice.如果您将笔记本代码转换为 Python 的全部目的是达到您的代码和笔记本可以长期维护的状态,那么仅 nbconvert 是不够的。 The only way to do that is by manually going through the codebase.唯一的方法是手动浏览代码库。
  2. Notebooks inherently promote writing code which is not maintainable ( https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g3d7fe085e7_0_21 ).笔记本天生就提倡编写不可维护的代码( https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g3d7fe085e7_0_21 )。 Using nbconvert on top might just prove to be a bandaid.在顶部使用 nbconvert 可能只是被证明是一个创可贴。 Specific examples of where it promotes not-so-maintainable code are imports might be sprayed throughout, hard coded paths are not in one simple place to view, class abstractions might not be present, etc.它促进不易维护的代码的具体例子是导入可能会被喷洒,硬编码路径不是在一个简单的地方查看,类抽象可能不存在,等等。
  3. nbconvert still mixes execution code and library code. nbconvert 仍然混合执行代码和库代码。
  4. Comments are still not present (probably were not in the notebook).评论仍然不存在(可能不在笔记本中)。
  5. There is still a lack of unit tests etc.仍然缺乏单元测试等。

So to summarize, there is not good way to out of the box convert python notebooks to maintainable, robust python modularized code, the only way is to manually do surgery.所以总而言之,开箱即用地将python笔记本转换为可维护、健壮的python模块化代码并没有什么好的方法,唯一的方法是手动进行手术。

You can use the following script to convert jupyter notebook to Python script, or view the code directly.您可以使用以下脚本将 jupyter notebook 转换为 Python 脚本,或直接查看代码。

To do this, write the following contents into a file cat_ipynb , then chmod +x cat_ipynb .为此,请将以下内容写入文件cat_ipynb ,然后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或者直接用vi显示

cat_ipynb your_notebook.ipynb | view -

  1. Go to https://jupyter.org/转到https://jupyter.org/
  2. click on nbviewer点击nbviewer
  3. Enter the location of your file and render it.输入文件的位置并渲染它。
  4. Click on view as code (shown as < />)点击view as code(显示为< />)

一种方法是在 Colab 上上传您的脚本并从File -> Download .py以 .py 格式下载它

You can run a .py file in the same directory:您可以在同一目录中运行 .py 文件:

import json

files = ["my_first_file_name.ipynb", "my_second_file_name.ipynb"]

for file in files:
    code = json.load(open(file))
    py_file = open(f"{file}.py", "w+")

    for cell in code['cells']:
        if cell['cell_type'] == 'code':
            for line in cell['source']:
                py_file.write(line)
            py_file.write("\n")
        elif cell['cell_type'] == 'markdown':
            py_file.write("\n")
            for line in cell['source']:
                if line and line[0] == "#":
                    py_file.write(line)
            py_file.write("\n")

    py_file.close()

I rewrite this code from Syrtis Major's answer.我根据 Syrtis Major 的回答重写了这段代码。

Convert the Ipynb dir files to .py将 Ipynb 目录文件转换为 .py

import os

for fname in os.listdir():
    if fname.endswith('ipynb'):
        os.system(f'jupyter nbconvert {fname} --to python')

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). Jupytext 允许在命令行上进行这种转换,重要的是,您可以再次从脚本返回到笔记本(甚至是已执行的笔记本)。 See here .这里

Copy all the (''.ipynb) files in the Desired folder then execute:复制 Desired 文件夹中的所有 (''.ipynb) 文件,然后执行:

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))

If this is a one-off, follow eg @kikocorreoso depending if you want to use command line or gui.如果这是一次性的,请遵循例如@kikocorreoso,具体取决于您是要使用命令行还是 gui。

However, if you want some solution that will maintain a synchronized version of the .py and the .ipynb you really should consider using jupytext as also pointed out by @Wayne但是,如果您想要一些能够保持 .py 和 .ipynb 同步版本的解决方案,您真的应该考虑使用jupytext ,正如@Wayne 所指出的那样

Run conda install jupytext or pip install jupytext运行conda install jupytextpip install jupytext

Then do: jupytext --set-formats ipynb,py <file>.ipynb然后执行: jupytext --set-formats ipynb,py <file>.ipynb

To keep it synchronized to the .py file:要使其与 .py 文件保持同步:

jupytext --set-formats ipynb,py <file>.ipynb --sync

This will make sure jupyter keeps the two files in sync when saving from now on...这将确保 jupyter 从现在开始保存时保持两个文件同步......

Last note: If you are a gui person, after running the installation command for jupytext, everything else can be done from the gui as well File-->Jupytext-->pair Notebook with light Script :最后说明:如果您是 gui 人,在运行 jupytext 的安装命令后,其他一切都可以从 gui 完成File-->Jupytext-->pair Notebook with light Script 在此处输入图像描述

jupyter nbconvert [filename].ipynb --no-prompt --to python

The above code will generate [filename].py in the same directory以上代码会在同目录下生成[filename].py

My version of Jupyter Notebook, 3.3.2, has this option on the File Menu:我的 Jupyter Notebook 版本 3.3.2 在文件菜单上有这个选项: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM