2013-07-31 13 views

答えて

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') 

しかし、それはそのスマートではないですし、それが1つのIPythonノートブックのセルへのpythonファイルからすべてのコードを配置します。しかし、あなたはいつも少しの解析をすることができます。

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') 

編集:細胞分裂を空白行は、モジュールレベルの命令(関数、変数またはクラス定義、インポートなどの前に現れるたびにトリガされる前のコードで解析

を説明します)。これは、インデントされていない行が表示され、空白行が先行している場合に表示されます。だから、2つのトップレベルの定義は唯一の存在であるため、二つのセルになります

import time 

import datetime 

は二つのセル、およびまた

class Test(objet): 

    def __init__(self, x): 

     self.x = x 

    def show(self): 

     print(self.x) 

class Foo(object): 
    pass 

次のようになります。

import time 
import datetime 

は、単に一つのセルになりますが、 (インデントされていない行)が空白行で始まります(ファイル内の最初の行は、新しいセルを開始する必要があるため、空白行が先行すると見なされます)。

+0

これは便利です。セル分割がトリガーされたときに簡単な解答を追加することはできますか? – user2304916

+0

簡単な説明が追加されました。 –

+0

私は、pythonファイルをノートブックに変換するつもりはなく、pythonスクリプトを使って一連のノートを書きます。 IPython.nbformat.currentは私の後ろのもののように見えます。ありがとう! – alex

関連する問題