How to use IPython Notebooks in Blog Posts

By Max Candocia

|

November 08, 2017

If you want to share an IPython notebook on a site other than GitHub, you can use a handy command to convert it to HTML:

ipython nbconvert --to html example.ipynb --template basic

At this point, though, a change in style is needed. It doesn't have any of the color formatting and is not aligned the way you would expect it. Thankfully it has most of the class tags needed to properly alter it. I use ipynb.css as a stylesheet for this purpose:

blockquote{
padding-left:4px;
border-left:2px solid #505050;
}
div#notebook{
margin-top:50px;
margin-bottom:100px;
}
div.cell{
max-width:60em;
margin-left:auto;
margin-right:auto;

}
div.input_prompt, div.output_prompt{
margin-left:-11ex;
}
div.input, div.output_wrapper{
margin-top:1em;
margin-bottom:1em;
}
div.text_cell{
margin-top:-2px;
margin-bottom:-2px;
padding-top:2px;
padding-bottom:2px;
border-collapse:collapse;
border-top:none;
border-bottom:none;
}

/*hide anchor links that are generated for headers*/
.anchor-link{display:none;}

/*color styles*/

/*box around content*/
div.hl-ipython2{
background-color:#EEE;
padding:4px;
border-width:1px;
border-color:#BBB;
border-style:solid;
}
/*imports*/
span.kn{color:forestgreen;font-weight:bold;}
/*multi-line text*/
span.sd{color:DarkRed;}
/*"self" and boolean args*/
span.bp{color:blue;}
/*comment*/
span.c1{color:forestgreen;}
/*function names*/
span.k{color:#2A3;font-weight:bold;}
/*parentheses and brackets and commas*/
span.p{color:#111;}
/*regular string*/
span.s1{color:DarkRed;}
/*number*/
span.mi{color:#3A4;}
/*function name*/
span.nf{color:blue;}
/*decorator*/
span.nd{color:#A18;}
/*., *, +, =, +=, etc.*/
span.o{}
/*arguments*/
span.n{}

/*style for code from errors*/
span.ansi-red-fg{color:#C22;}
span.ansi-green-fg{color:#2C2;}
span.ansi-cyan-fg{color:cyan;}
span.ansi-blue-fg{color:blue;}
span.ansi-green-intense-fg{color:#2C2;}

/*also used in warnings*/
div.output_stderr{
background-color:#DBB;
}

Example iPython Notebook

Below is a simple example of an iPython notebook embedded in HTML. For another example, see one of my recent posts: Reinforcement Learning Demo with Keras.

In [1]:
from collections import Counter
import json
import warnings

def empty_counter_warning(func):
    def inner_func(*args):
        for arg in args:
            if isinstance(arg, Counter):
                if len(arg)==0:
                    warnings.warn('You are using an empty counter object...')
        return func(*args)
    return inner_func

class DotCounter(Counter):
    """
    class that allows counter objects to have elements accessed by dots
    rather than just brackets
    """
    __getattr__ = Counter.__getitem__
    __setattr__ = Counter.__setitem__
    __delattr__ = Counter.__delitem__
    
    @empty_counter_warning
    def __str__(self):
        return json.dumps(self, indent=4)
    
    
no_stuff = DotCounter()
stuff = DotCounter({'apple':2,
                    'orange':1})
In [2]:
print no_stuff
{}
/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:10: UserWarning: You are using an empty counter object...
  # Remove the CWD from sys.path while we load stuff.
In [3]:
#just printing out a few things
print stuff.apple
stuff.orange += 1
print stuff.banana + 2
stuff.lemon+=1
print stuff
2
2
{
    "orange": 2, 
    "lemon": 1, 
    "apple": 2
}
In [4]:
#force an error
1 + 'a'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-f794df300990> in <module>()
      1 #force an error
----> 2 1 + 'a'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

External Code

Here is the code on GitHub in case you wanted to try using the same files: https://github.com/mcandocia/examples/tree/master/ipynb_format_example


Tags: 

Recommended Articles

What Age do Kids Start Going Trick-or-Treating, and When do They Stop?

When do kids start going trick or treating, and when are they "too cool" to continue going? Using survey data and a variety of statistical techniques, answers to these questions can be found to a certain level of statistical confidence.

Converting Garmin FIT Files to CSV

Garmin GPS data can be converted to CSV files with important workout information, including location, heart rate, and elevation. I provide sources and a script for processing them using Python 3.