Skip to content

Commit

Permalink
Makes this Python 2 and 3 compatible, small typo fix
Browse files Browse the repository at this point in the history
Python 2 wasn't happy with list unpacking so that's removed
in favour of a simple iteration
  • Loading branch information
Dimitar Tasev committed Jan 30, 2020
1 parent 26ffae1 commit 092494d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 24 deletions.
22 changes: 2 additions & 20 deletions example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
" Code by default will be put into code cells\n",
"\n",
" * To make a markdown cell, prefix the comment line with with '#|' or '# |'\n",
" * To split a code cell, add a line beginning with '#-' or '# -#"
" * To split a code cell, add a line beginning with '#-' or '# -'"
]
},
{
Expand Down Expand Up @@ -100,25 +100,7 @@
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
}
},
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
13 changes: 9 additions & 4 deletions py2nb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import os

import nbformat.v4

CODE_SPLIT_CHARS = ['#-', '# -']
ACCEPTED_CHARS = ['#-', '# -']
MARKDOWN_CHARS = ['#|', '# |']

ACCEPTED_CHARS.extend(MARKDOWN_CHARS)

def new_cell(nb, cell, markdown=False):
""" Create a new cell
Expand All @@ -35,6 +35,11 @@ def new_cell(nb, cell, markdown=False):
nb.cells.append(cell)
return ''

def str_starts_with(string, options):
for opt in options:
if string.startswith(opt):
return True


def convert(script_name):
""" Convert the python script to jupyter notebook"""
Expand All @@ -43,9 +48,9 @@ def convert(script_name):
code_cell = ''
nb = nbformat.v4.new_notebook()
for line in f:
if line.startswith((*CODE_SPLIT_CHARS, *MARKDOWN_CHARS)):
if str_starts_with(line, ACCEPTED_CHARS):
code_cell = new_cell(nb, code_cell)
if line.startswith((*MARKDOWN_CHARS, )):
if str_starts_with(line, MARKDOWN_CHARS):
# find the first occurence of |
# and add the rest of the line to the markdown cell
markdown_cell += line[line.index('|') + 1:]
Expand Down

0 comments on commit 092494d

Please sign in to comment.