您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

是否有IPython笔记本API?

5b51 2022/1/14 8:20:41 python 字数 3778 阅读 441 来源 www.jb51.cc/python

我想从python脚本生成几个笔记本.是否有编写IPython笔记本的API?最佳答案有,你可以这样做:import io from IPython.nbformat import current def convert(py_file, ipynb_file): with io.open(py_file, 'r', encoding='utf-8

概述

我想从python脚本生成几个笔记本.是否有编写IPython笔记本的API?

import io
from IPython.nbformat import current

def convert(py_file,ipynb_file):
    with io.open(py_file,'r',encoding='utf-8') as f:
        notebook = current.reads(f.read(),format='py')
    with io.open(ipynb_file,'w',encoding='utf-8') as f:
        current.write(notebook,f,format='ipynb')

convert('test.py','test.ipynb')

但它并不那么聪明,它会将python文件中的所有代码放入一个IPython Notebook单元格中.但是你总是可以做一些解析.

import io
import re
from IPython.nbformat import current

def parse_into_cells(py_file):
    with io.open(py_file,encoding='utf-8') as f:
        data = f.readlines()
    in_cell = True
    cell = ''
    for line in data:
        if line.rstrip() == '':
            # If a blank line occurs I'm out of the current cell
            in_cell = False
        elif re.match('^\s+',line):
            # Indentation,so nope,I'm not out of the current cell
            in_cell = True
            cell += line
        else:
            # Code at the beginning of the line,so if I'm in a cell just
            # append it,otherwise yield out the cell and start a new one
            if in_cell:
                cell += line
            else:
                yield cell.strip()
                cell = line
                in_cell = True
    if cell != '':
        yield cell.strip()

def convert(py_file,ipynb_file):
    # Create an empty notebook
    notebook = current.reads('',format='py')
    # Add all the parsed cells
    notebook['worksheets'][0]['cells'] = list(map(current.new_code_cell,parse_into_cells(py_file)))
    # Save the notebook
    with io.open(ipynb_file,format='ipynb')

convert('convert.py','convert.ipynb')

编辑:解释解析

在前面的代码中,只要在模块级指令(函数,变量或类定义,导入等)之前出现空行,就会触发单元格拆分.这就是每当我看到一条没有缩进的行并且前面有一个空行时).所以:

import time
import datetime

将只是一个单元格,但是:

import time

import datetime

将是两个细胞,也是

class Test(objet):

    def __init__(self,x):

        self.x = x

    def show(self):

        print(self.x)

class Foo(object):
     pass

将是两个单元格,因为只有两个顶级定义(没有缩进的行)前面有一个空行(文件中的第一行被认为前面有一个空行,因为它必须启动一个新单元格) .

总结

以上是编程之家为你收集整理的是否有IPython笔记本API?全部内容,希望文章能够帮你解决是否有IPython笔记本API?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶