Created
August 10, 2013 19:33
-
-
Save rossant/6201826 to your computer and use it in GitHub Desktop.
Convert an IPython notebook to console-like text output.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Conversion from JSON to TXT. | |
import os | |
import json | |
def process_input(cell): | |
if 'prompt_number' not in cell: | |
return '' | |
prefix = "In [{0:s}]: ".format(str(cell['prompt_number'])) | |
spaces = ' ' * len(prefix) | |
contents = prefix + cell['input'][0] | |
for line in cell['input'][1:]: | |
contents += spaces + line + '' | |
return contents | |
def process_outputs(cell): | |
if not cell['outputs']: | |
return '' | |
prefix = "Out[{0:d}]: ".format(cell['prompt_number'],) | |
spaces = ' ' * len(prefix) | |
contents = '' | |
for output in cell['outputs']: | |
if output['output_type'] == 'pyout': | |
if len(contents) > 0: | |
contents += spaces | |
else: | |
contents += prefix | |
contents += ''.join(output['text']) + '' | |
#contents += '\n' | |
return contents | |
def process_cell(cell): | |
if cell['cell_type'] == 'code': | |
contents = process_input(cell) | |
contents += '\n' | |
contents += process_outputs(cell) | |
elif cell['cell_type'] == 'markdown': | |
contents = '' + ''.join(cell['source']) + '\n' | |
return contents | |
def process_cells(cells): | |
return '\n'.join(map(process_cell, cells)) | |
def convert(filename): | |
filename_to = os.path.splitext(filename)[0] + '.txt' | |
with open(filename, 'r') as f: | |
contents = json.load(f) | |
text = process_cells(contents['worksheets'][0]['cells']) | |
with open(filename_to, 'w') as f: | |
f.write(text) | |
def main(): | |
import sys | |
files = sys.argv[1:] | |
if not files: | |
files = filter(lambda f: f.endswith('.ipynb'), os.listdir('.')) | |
for file in files: | |
convert(file) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment