Python 将Jupyter笔记本(ipynb)文件中的函数转换为单个.py文件

Python 将Jupyter笔记本(ipynb)文件中的函数转换为单个.py文件,python,jupyter-notebook,Python,Jupyter Notebook,如何将ipynb文件目录中的函数转换为单个.py文件?这将使测试后在单片jupyter笔记本中导入变得容易。以下是相关代码 # program to convert functions in cells to indivdiual .py files # the first line of the cell containing function to be converted should have # filename.py import json from os import listd

如何将ipynb文件目录中的函数转换为单个.py文件?这将使测试后在单片jupyter笔记本中导入变得容易。

以下是相关代码

# program to convert functions in cells to indivdiual .py files
# the first line of the cell containing function to be converted should have
# filename.py

import json
from os import listdir

fs = listdir() # get the filenames

# make an exclusion list
magics = %lsmagic
magic_words = [s for s in str(magics).split(' ') if s not in '' if '%' in s[0]]
magic_words = [s for s in magic_words if s != '%']
exclude = ['util.startLoop()'] + magic_words

# Ignore ipynb files beginning with '_'
ipyfilelist = [f for f in fs if f[-6:].upper() == '.IPYNB' if f[0] != '_']

code_cells = []
for file in ipyfilelist:
    with open(file) as datafile:
        code = json.load(datafile)
        code_cells.append([cell['source'] for cell in code['cells'] if cell['cell_type'] == 'code'])

codes = [cell for cells in code_cells for cell in cells if cell]

code_dict = {pycode[0][2:-1]:pycode for pycode in codes if pycode[0][-4:] == '.py\n'}

for k, v in code_dict.items():
    with open(k, 'w') as f:
        for line in v:
            if not any(word in line for word in exclude):
                f.write(line)