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

相关推荐
培培说证5 分钟前
2026 高职计算机专业考证选择哪个更实用?
python
ASD123asfadxv21 分钟前
LCD屏幕表面缺陷检测系统凹陷识别与定位技术分析
python
Ulyanov29 分钟前
大规模战场数据与推演:性能优化与多视图布局实战
开发语言·python·性能优化·tkinter·pyvista·gui开发
tjjucheng30 分钟前
小程序定制开发哪家口碑好
python
tjjucheng32 分钟前
小程序定制开发源头厂家
python
过期的秋刀鱼!1 小时前
机器学习-带正则化的成本函数-
人工智能·python·深度学习·算法·机器学习·逻辑回归
郝学胜-神的一滴1 小时前
机器学习数据预处理:归一化与sklearn的MinMaxScaler详解
人工智能·python·程序人生·机器学习·性能优化·sklearn
weixin_462446231 小时前
Python 使用 Chainlit + Ollama 快速搭建本地 AI 聊天应用
人工智能·python·ollama·chainlit
小北方城市网1 小时前
SpringBoot 集成 MinIO 实战(对象存储):实现高效文件管理
java·spring boot·redis·分布式·后端·python·缓存
UR的出不克1 小时前
Python实现SMZDM数据处理系统:从爬虫到数据分析的完整实践
爬虫·python·数据分析