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

相关推荐
Iridescent11214 分钟前
Iridescent:Day28
python
m0_726365835 分钟前
大力学习台灯T6/T6Pro 救砖实战:macOS/Windows 用 mtkclient 从 Fastboot 无限重启完整恢复(含固件下载地址)
python·github·智能硬件
free-elcmacom19 分钟前
机器学习高阶教程<7>Transformer原理全景解读:从“序列困境”到“注意力革命”
人工智能·python·机器学习·transformer
RwwH21 分钟前
PyCharm虚拟环境创建
ide·python·pycharm
码海踏浪26 分钟前
JMeter 时间函数合集
开发语言·python
serve the people27 分钟前
tensorflow 深度解析 Sequential 模型的输入形状指定
人工智能·python·tensorflow
SunnyDays101128 分钟前
Python 实现 PDF 文档压缩:完整指南
linux·开发语言·python
长安牧笛28 分钟前
设计考研党备考开支追踪程序,记录教材,网课,报名费支出,按科目统计花费,优化备考预算分配。
python
长空任鸟飞_阿康32 分钟前
LangChain 技术栈全解析:从模型编排到 RAG 实战
前端·python·langchain
江上鹤.14833 分钟前
Day42Dataset和Dataloader
python