说明
在探索的时候用ipynb比较方便,不过部署的时候通常是py形式,本篇做一个简单的函数来提取ipynb中的有用内容,保存为py。
内容
做一个字符串口令, 函数将ipynb中含有此口令的单元格提取出来
假设样例为
ipynb可以用json方法导入
我们可以判定哪些单元格有执行print(keepme)
命令的行,将这些代码单元格抽取出来,再写入一个py文件就好了。
函数
import json
# 读取一个ipynb,抽取含有口令行(print(keepme))的代码单元格,保存为py
def ipynb2py(source_file,target_file, source_path = './', target_path='./', token_line = 'print(keepme)', encoding='utf-8'):
with open(source_path+ source_file, 'r', encoding=encoding) as f:
res_dict = json.loads(f.read())
# 单元格
all_cells = res_dict['cells']
lines = []
# 行首
lines.append(['# Auto Write from Ipynb\n'])
# 选择单元格
for cell in all_cells:
sel_tag = 0
if cell['cell_type'] == 'code':
tem_cell = []
for line in cell['source']:
# 去空格
line1 = line.replace(' ','')
if token_line in line1:
sel_tag = 1
else:
tem_cell.append(line)
if sel_tag ==1:
# 单元间隔
tem_cell.append('\n###cell split###\n')
lines.append(tem_cell)
lines_flat = sum(lines, [])
py_res = ''.join(lines_flat)
with open(target_path + target_file , 'w', encoding=encoding) as fout:
fout.write(py_res)
return True
测试
ipynb2py('test3_for_extract.ipynb','aa.py')