, 당신은 할 수 있습니다. 그러나 당신은 항상 파싱을 약간 할 수 있습니다.
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
은 하나의 셀 수 있지만 것인가 :
import time
import datetime
두 개의 세포 및 것인가도
class Test(objet):
def __init__(self, x):
self.x = x
def show(self):
print(self.x)
class Foo(object):
pass
두 최고 수준의 정의가 있기 때문에 두 개의 셀이 될 것입니다 (들여 쓰기되지 않은 행) 앞에 공백 행이 있습니다 (파일의 첫 x 째 행은 새 셀을 시작해야하기 때.에 공 i 행이 선행 된 것으로 간주됩니다).
유용합니다. 셀 분할이 트리거 될 때 간단한 해설을 추가 할 수 있습니까? – user2304916
간단한 설명을 추가했습니다. –
파이썬 파일을 노트북으로 변환하는 대신 파이썬 스크립트를 사용하여 일련의 노트를 작성합니다. IPython.nbformat.current는 내가 한 것처럼 보입니다. 감사! – alex