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

相关推荐
zh路西法9 分钟前
【Qwen2.5本地部署】超简单pytorch-gpu部署教程
人工智能·pytorch·python
狐狐生风17 分钟前
LangGraph Human-in-the-loop 全解
python·langchain·prompt·langgraph·agentai
倒霉熊dd28 分钟前
Python 学习(第二部分:函数、模块与面向对象编程)
前端·数据库·python
铁皮哥32 分钟前
【力扣题解】LeetCode 25. K 个一组翻转链表
java·数据结构·windows·python·算法·leetcode·链表
lbb 小魔仙1 小时前
告别腾讯会议40分钟限制:用ToDesk协作版开在线会议,免费不限时远程会议新方案
python·langchain·jenkins
凯瑟琳.奥古斯特1 小时前
PyTorch动态计算图详解
人工智能·pytorch·python·深度学习
一个数据大开发1 小时前
企业知识工程的三条路线:Neo4j 知识中台、Agent + Action 与本体原生 Runtime
大数据·python·neo4j
没有感情的robot1 小时前
网页录制方法总结
python
m0_738120721 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(二)
python·网络协议·tcp/ip·安全·网络安全
Fleshy数模1 小时前
从课堂视频到结构化教学数据:基于语音识别与 LLM 的智能处理方案
ide·macos·xcode