[英]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'
根据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
选项将其转换为这些格式中的任何一种:
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.04在Ubuntu 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
Use jupyter nbconvert command to convert to different format使用jupyter nbconvert命令转换为不同的格式
Source file pro.ipynb源文件 pro.ipynb
$ jupyter nbconvert --to asciidoc pro.ipynb
$ jupyter nbconvert --to pdf pro.ipynb
$ jupyter nbconvert --to python pro.ipynb
Convert ipynb project through python code use savefig method of pyplot :通过 python 代码转换 ipynb 项目使用pyplot的savefig方法:
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 图像:
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:但是,由于个人使用它,我建议不要使用它,原因如下:
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 -
一种方法是在 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')
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 jupytext
或pip 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.