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

相关推荐
JAVA学习通1 分钟前
AI Agent 工具调用机制深度解析与 Spring Boot 工程集成实战(2026版)
java·人工智能·spring boot·python·spring
亿牛云爬虫专家2 分钟前
解决 Python 爬虫代理 407 错误:基于 urllib3 更新与爬虫代理的实战指南-2
爬虫·python·爬虫代理·authentication·urllib3·407·base64 编码
m0_640309303 分钟前
CSS中如何让浮动元素撑开父容器_深度解析清除浮动
jvm·数据库·python
2301_816660213 分钟前
Golang bufio怎么读取用户输入_Golang标准输入读取教程【详解】
jvm·数据库·python
WJ.Polar5 分钟前
Ansible任务控制
linux·运维·网络·python·ansible
泰迪智能科技015 分钟前
图书教材推荐|Python网络爬虫技术(第2版)(微课版)
开发语言·爬虫·python
解救女汉子7 分钟前
Golang如何创建和删除目录_Golang目录操作教程【完整】
jvm·数据库·python
m0_5887584810 分钟前
CSS如何修复Safari下边框圆角溢出问题_利用background-clip属性修正
jvm·数据库·python
m0_7349497912 分钟前
uni-app怎么做横向滚动导航 uni-app滚动菜单Tab实现教程【代码】
jvm·数据库·python
2301_7751481513 分钟前
SQL如何检查字符串是否存在:INSTR与LOCATE函数使用
jvm·数据库·python