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

相关推荐
测试开发-学习笔记9 分钟前
Android studio安装
android·ide·android studio
IT知识分享15 分钟前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python
lunzi_082620 分钟前
【学习笔记】《Python编程 从入门到实践》第8章:函数定义、参数传递与模块导入
笔记·python·学习
ABAP-張旺33 分钟前
ABAP:Visual Studio Code官方插件安装教程
ide·vscode·编辑器
杨运交37 分钟前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证1 小时前
2026财务岗位如何快速提升自身能力
python
努力攻坚操作系统1 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
godspeed_lucip1 小时前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python
Metaphor6922 小时前
使用 Python 给 PDF 设置背景色或背景图
数据库·python·pdf