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

相关推荐
bst@微胖子29 分钟前
Python高级语法之selenium
开发语言·python·selenium
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
罗政7 小时前
冒险岛079 V8 整合版源码搭建教程+IDEA启动
java·ide·intellij-idea
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
小哥山水之间8 小时前
在 Python 中操作 Excel 文件
开发语言·python·excel
艾斯比的日常8 小时前
VSCode 实用快捷键
ide·vscode·编辑器
Galaxy_12298 小时前
vscode远程报错:Remote host key has changed,...
ide·vscode·编辑器