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

相关推荐
日出等日落17 小时前
用 Kavita实现我的远程数字书屋搭建记!
java·开发语言·ide·vscode·编辑器
berryyan17 小时前
🚀 Windows + RTX 5090 + ComfyUI 桌面版 安装 SageAttention 完全手册
人工智能·python
性感程序员在线debug17 小时前
Python yield 原理
python
Alan GEO实施教练17 小时前
实用新型专利申请代理机构选择:关键考量因素与实操要点讲解
java·开发语言·python
闲云lazycloud17 小时前
08-Java工程师的Python第八课-框架入门
python
是真的小外套17 小时前
第十一章:Flask入门之从零构建Python Web应用
前端·python·flask
Westward-sun.17 小时前
NLP 词向量实战:PyTorch 从零实现 CBOW(Word2Vec)全流程拆解
人工智能·pytorch·python·深度学习·自然语言处理·word2vec
青瓷程序设计17 小时前
基于YOLO的安全帽佩戴检测系统~Python+模型训练+2026原创+YOLO算法
python·算法·yolo
badhope17 小时前
2025年3月AI领域纪录:从模型开源到智能体价值重估——风云变幻DLC
人工智能·python·深度学习·计算机视觉·数据挖掘
一见18 小时前
vscode等的“Go Team at Google”插件
ide·vscode·golang