From 092494d4eb46bfe6de56f3ee435e3fcecc0133e6 Mon Sep 17 00:00:00 2001 From: Dimitar Tasev Date: Thu, 30 Jan 2020 08:44:38 +0000 Subject: [PATCH] Makes this Python 2 and 3 compatible, small typo fix Python 2 wasn't happy with list unpacking so that's removed in favour of a simple iteration --- example.ipynb | 22 ++-------------------- py2nb | 13 +++++++++---- 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/example.ipynb b/example.ipynb index 3dcbe66..c09fe64 100644 --- a/example.ipynb +++ b/example.ipynb @@ -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 '# -'" ] }, { @@ -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 } diff --git a/py2nb b/py2nb index 7b84ae9..53e3ea6 100755 --- a/py2nb +++ b/py2nb @@ -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 @@ -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""" @@ -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:]