如何将 Jupyter Notebook (.ipynb) 文件转换为 Python (.py) 文件

概要:编写python代码运行将.ipynb转化为.py

python 复制代码
import json

def convert_ipynb_to_py(ipynb_file, py_file):
    with open(ipynb_file, 'r',encoding='utf-8') as f:
        notebook = json.load(f)

    with open(py_file, 'w',encoding='utf-8') as f:
        for cell in notebook['cells']:
            if cell['cell_type'] == 'code':
                f.write(''.join(cell['source']) + '\n\n')


convert_ipynb_to_py('counterfactual_adversarial_example_generation.ipynb', 'counterfactual_adversarial_example_generation.py')

然后执行这个代码就行

别的就是下载一个jupyter Note ,进行转化

或者在命令行里下载个jupyter 然后输入命令进行转换

python 复制代码
pip install jupyter

然后,运行以下命令将你的 .ipynb 文件转换为 .py 文件------记得进入到你所在的.ipynb 文件目录下:

python 复制代码
jupyter nbconvert --to script your_notebook.ipynb

所生成的文件在你所在的文件下

参考博客https://blog.csdn.net/qq_69218005/article/details/131339237

相关推荐
IVEN_8 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang9 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮9 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling9 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮12 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽13 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers