是否有IPython笔记本API?

是否有IPython笔记本API?,第1张

概述我想从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 iofrom IPython.nbformat import currentdef 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 ioimport refrom IPython.nbformat import currentdef 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 timeimport datetime

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

import timeimport 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?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1205303.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存