将jupyter转换为python文件

一直在思考是否可以将jupyter转化为python,一直都未尝试,但是最近在网上找了一些资料,尝试了一下。相应的代码如下:

python 复制代码
# 简单的将jupyter转换为python文件
import argparse
import os
import subprocess
def convert(input_path, output_path):
    subprocess.call(['jupyter', 'nbconvert', '--to', 'script', input_path, '--output', output_path])
def cleanup(path):
    skip_lines_startwith = ('Image(filename=', '# In[', '# <hr>', 'from IPython.display import Image', 'get_ipython()', '# <br>')
    clean_content = []
    imports = []
    existing_imports = set()
    with open(path, 'r', encoding="utf8") as f:
        next(f)
        next(f)
        for line in f:
            line = line.rstrip(' ')
            if line.startswith(skip_lines_startwith):
                continue
            if line.startswith('import ') or (
                    'from ' in line and 'import ' in line):
                if 'from __future__ import print_function' in line:
                    if line != imports[0]:
                        imports.insert(0, line)
                else:
                    if line.strip() not in existing_imports:
                        imports.append(line)
                        existing_imports.add(line.strip())
            else:
                clean_content.append(line)
    clean_content = ['# coding: utf-8\n\n\n'] + imports + clean_content
    with open(path, 'w', encoding="utf8") as f:
        for line in clean_content:
            f.write(line)
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Convert Jupyter notebook to Python script.', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('-i', '--input', required=True, help='Path to the Jupyter Notebook file')
    parser.add_argument('-o', '--output', required=True, help='Path to the Python script file')
    parser.add_argument('-v', '--version', action='version', version='v. 0.1')
    args = parser.parse_args()
    convert(input_path=args.input,output_path=os.path.splitext(args.output)[0])
    cleanup(args.output)

后续如果需要将python转换为jupyter的文件,在更新相应的代码

相关推荐
2401_82889064几秒前
实现扩散模型 Stable Diffusion - MNIST 数据集
人工智能·python·深度学习·stable diffusion
jz_ddk12 分钟前
[指南] Python循环语句完全指南
开发语言·python·continue·循环·for·while·break
Evand J21 分钟前
【Python代码例程】长短期记忆网络(LSTM)和无迹卡尔曼滤波(UKF)的结合,处理复杂非线性系统和时间序列数据
python·lstm·滤波
workflower1 小时前
易用性和人性化需求
java·python·测试用例·需求分析·big data·软件需求
嚯嚯歪1 小时前
攻克腾讯 TCaptcha 滑块验证码:纯 HTTP 协议逆向实战
爬虫·python·逆向·验证码识别
じ☆冷颜〃2 小时前
随机微分层论:统一代数、拓扑与分析框架下的SPDE论述
笔记·python·学习·线性代数·拓扑学
程序员敲代码吗2 小时前
提升Python编程效率的五大特性
开发语言·python
List<String> error_P3 小时前
Python蓝桥杯常考知识点-模拟
开发语言·python·蓝桥杯
比奇堡鱼贩3 小时前
python第五次作业
开发语言·前端·python
码农小韩4 小时前
AIAgent应用开发——DeepSeek分析(二)
人工智能·python·深度学习·agent·强化学习·deepseek