2013-07-31 34 views

Trả lời

4

Có, bạn có thể làm:

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

Nhưng nó không phải là thông minh và nó sẽ đặt tất cả các mã từ file python vào một tế bào Notebook IPython. Nhưng bạn luôn có thể làm một chút phân tích cú pháp.

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

Edit: Giải thích về phân tích cú pháp

Trong đoạn mã trước một sự chia rẽ tế bào được kích hoạt bất cứ khi nào một dòng trống xuất hiện trước một hướng dẫn cấp module (chức năng, biến hoặc lớp định nghĩa, nhập khẩu, vv .). Đó là bất cứ khi nào tôi nhìn thấy một dòng mà không phải là thụt vào và được bắt đầu bằng một dòng trống). Vì vậy:

import time 
import datetime 

Sẽ là chỉ là một tế bào, nhưng:

import time 

import datetime 

Sẽ là hai tế bào, và cũng

class Test(objet): 

    def __init__(self, x): 

     self.x = x 

    def show(self): 

     print(self.x) 

class Foo(object): 
    pass 

sẽ có hai tế bào kể từ khi chỉ có hai định nghĩa cấp cao nhất (các dòng không được thụt lề) trước dòng trống (dòng đầu tiên trong tệp được coi là bắt đầu bằng một dòng trống vì nó phải bắt đầu một ô mới).

+0

Điều đó hữu ích. Bạn có thể thêm vào câu trả lời một bản tóm tắt ngắn gọn khi phân chia ô được kích hoạt không? – user2304916

+0

Đã thêm giải thích đơn giản. –

+0

Tôi không có ý định chuyển đổi tệp python sang sổ ghi chép, mà là viết một loạt sổ ghi chép bằng cách sử dụng tập lệnh python. các IPython.nbformat.current trông giống như những gì tôi đã sau. cảm ơn! – alex