将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的文件,在更新相应的代码

相关推荐
长沙三为智能科技3 分钟前
多平台内容矩阵怎么配合GEO:4层分工与3条去重规则
python·aigc·geo优化
ycydynq4 分钟前
django 添加信息时,对外键设置条件
数据库·python·django
清水白石00810 分钟前
Python 安装与环境配置:Windows、macOS、Linux 完整指南(第2集)
windows·python·macos
一只QAQ12 分钟前
python语法学习
linux·python·学习
全栈陈序员21 分钟前
【Python】基础语法入门(二十八)—— 数据库操作入门:用 SQLite 持久化数据
数据库·人工智能·python
weixin_440401691 小时前
大数据技术-数据分析(EXcel+Python数据处理+SQL)
大数据·python·数据分析·excel
甜到心里的蛋糕1 小时前
AI 生成 MV 音频异响排查:频谱定位、片段替换与 Nginx 缓存
人工智能·python·nginx·ffmpeg·音视频·音频处理
2601_967980111 小时前
python中的静态方法和类方法
python·静态方法·类方法·实例化·方法调用
智购科技无人售货机厂家1 小时前
自动售货机物联网平台为什么会出现在线状态不一致?~YH
python·单片机·嵌入式硬件·django·pygame
飞Link10 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机