Converting to (not from) ipython Notebook format

后端 未结 10 993
刺人心
刺人心 2020-11-29 17:10

IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already ha

10条回答
  •  佛祖请我去吃肉
    2020-11-29 17:28

    Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.

    I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.

    The script handles only code cells. The exported .py does not contain much else, anyway.

    import nbformat
    from nbformat.v4 import new_code_cell,new_notebook
    
    import codecs
    
    sourceFile = "changeMe.py"     # <<<< change
    destFile = "changeMe.ipynb"    # <<<< change
    
    
    def parsePy(fn):
        """ Generator that parses a .py file exported from a IPython notebook and
    extracts code cells (whatever is between occurrences of "In[*]:").
    Returns a string containing one or more lines
    """
        with open(fn,"r") as f:
            lines = []
            for l in f:
                l1 = l.strip()
                if l1.startswith('# In[') and l1.endswith(']:') and lines:
                    yield "".join(lines)
                    lines = []
                    continue
                lines.append(l)
            if lines:
                yield "".join(lines)
    
    # Create the code cells by parsing the file in input
    cells = []
    for c in parsePy(sourceFile):
        cells.append(new_code_cell(source=c))
    
    # This creates a V4 Notebook with the code cells extracted above
    nb0 = new_notebook(cells=cells,
                       metadata={'language': 'python',})
    
    with codecs.open(destFile, encoding='utf-8', mode='w') as f:
        nbformat.write(nb0, f, 4)
    

    No guarantees, but it worked for me

提交回复
热议问题