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

相关推荐
程序设计实验室6 分钟前
Python网络请求库,从 requests 到 httpx
python
电商API&Tina10 分钟前
跨境电商如何接入1688官方寻源通接口?附接入流程
java·数据库·python·sql·oracle·json·php
Lyyaoo.25 分钟前
【Java基础面经】Java 注解的底层原理
java·开发语言·python
HAPPY酷26 分钟前
PyCharm 终极避坑指南:环境选择、镜像加速与包管理
ide·python·pycharm
如竟没有火炬34 分钟前
搜索二维矩阵
数据结构·python·算法·leetcode·矩阵
郝学胜-神的一滴42 分钟前
自动微分实战:梯度下降的迭代实现与梯度清零核心解析
人工智能·pytorch·python·深度学习·算法·机器学习
PILIPALAPENG1 小时前
第1周 Day 5:前端转型AI,回顾总结🎯
前端·人工智能·python
zzb15801 小时前
系统提示词-System Prompt 动态组装
人工智能·后端·python·prompt
hua_ban_yu1 小时前
新版本 idea 如何设置热部署
java·ide·intellij-idea
嫂子的姐夫1 小时前
34-自动化补环境和jsdom补环境
爬虫·python·逆向