将Jupyter Notebook(ipynb)文件中的功能转换为单个.py文件

时间:2019-04-16 14:32:25

标签: python jupyter-notebook

如何将ipynb文件目录中的功能转换为单个.py文件?这样可以很容易地在单片jupyter笔记本中进行测试后导入。

1 个答案:

答案 0 :(得分:1)

这是代码。...

# 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)