Python一些可能用的到的函数系列88 向量keepme 提取ipynb的内容

本文介绍了一种从Jupyter Notebook (ipynb) 文件中提取特定代码单元格的方法,并将其转换为Python (.py) 文件的过程。通过定义一个函数 `ipynb2py` 实现了这一转换,该函数能识别并抽取包含指定标记(如 `print(keepme)`)的代码段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明

在探索的时候用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')

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值