Python スクリプトからいくつかのノートブックを生成したいと思います。IPython ノートブックを作成するための API はありますか?
1629 次
1 に答える
4
あります。次のことができます。
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 ファイルから 1 つの IPython Notebook セルに配置します。しかし、いつでも少しの解析を行うことができます。
import io
import re
from IPython.nbformat import current
def parse_into_cells(py_file):
with io.open(py_file, 'r', 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, 'w', encoding='utf-8') as f:
current.write(notebook, f, format='ipynb')
convert('convert.py', 'convert.ipynb')
編集:解析の説明
前のコードでは、モジュール レベルの命令 (関数、変数またはクラスの定義、インポートなど) の前に空白行が表示されるたびにセル分割がトリガーされます。それは、インデントされておらず、前に空白行がある行を見るときです)。そう:
import time
import datetime
1 つのセルになりますが、次のようになります。
import time
import datetime
2つのセルになり、また
class Test(objet):
def __init__(self, x):
self.x = x
def show(self):
print(self.x)
class Foo(object):
pass
空行が前にある最上位の定義 (インデントされていない行) が 2 つしかないため、2 つのセルになります (ファイルの最初の行は、新しいセルを開始する必要があるため、前に空行があると見なされます)。 .
于 2013-08-01T18:14:18.817 に答える