如何将带单元格标记的PY格式文件转回IPYNB格式?
如何将带Jupyter单元格标记的PY文件转回分单元格的IPYNB文件?
完全可以实现拆分,核心是利用PY文件中# In[xxx]:这类标记来识别单元格的边界。下面提供一种简单直接的实现方式:
自定义Python脚本拆分并生成IPYNB
写一个小脚本遍历PY文件内容,按单元格标记分割代码块,再组装成标准的IPYNB格式(本质是JSON结构):
import json def py_to_ipynb(py_file_path, output_ipynb_path): # 读取PY文件内容 with open(py_file_path, 'r', encoding='utf-8') as f: all_lines = f.readlines() code_cells = [] current_code = [] for line in all_lines: # 匹配Jupyter单元格标记行 stripped_line = line.strip() if stripped_line.startswith('# In[') and stripped_line.endswith(']:'): # 把当前积累的代码作为一个单元格存入 if current_code: code_cells.append({ "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": current_code }) current_code = [] continue # 跳过标记行本身 current_code.append(line) # 处理最后一段代码 if current_code: code_cells.append({ "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": current_code }) # 构建IPYNB的标准JSON结构 notebook_structure = { "cells": code_cells, "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10" # 可根据你的Python版本调整 } }, "nbformat": 4, "nbformat_minor": 2 } # 写入IPYNB文件 with open(output_ipynb_path, 'w', encoding='utf-8') as f: json.dump(notebook_structure, f, indent=2) # 调用示例:替换为你的文件路径 py_to_ipynb("converted_file.py", "restored_notebook.ipynb")
脚本说明
- 脚本会逐行扫描PY文件,每遇到
# In[xxx]:标记就将之前的代码片段封装成一个独立的代码单元格 - 生成的IPYNB文件完全符合Jupyter的格式规范,打开后能看到拆分好的单元格
- 原PY文件中的注释、代码逻辑都会完整保留,不会被修改
内容的提问来源于stack exchange,提问作者AdityaMani
相关产品推荐
相关产品推荐

