Wei Zhang's Blog

24 Dec 2021

Add posts to Hugo blog using Jupyter notebook

In this post, I record some tips for using Jupyter notebook, which is a web-based tool for interactively editing, coding, and running Python code.

Jupytext, a plugin for Jupyter, enables version control in notebook and converting notebook to different formats. For example, to convert a python script into jupyter notebook, one uses the following command in a bash shell.

jupytext --to notebook input.py

A useful utility of Jupytext is that it allows us to pair notebook and python script. After pairing, we can focus on writing and testing python code in Jupyter notebook. All the changes will be automatically updated to the paired python script.

Beside Jupytext, nbconvert also converts notebook to various formats, e.g. PDF, Latex, html, Markdown. For instance, to convert notebook to markdown format, we can use

jupyter nbconvert --to markdown input.ipynb

To include a Jupyter notebook to Hugo blog, one needs to first convert the notebook to Markdown format for Hugo. The package nb2hugo makes the conversion more automatically. To use it, after installation, I did the following two steps under the root directory of my Hugo blog.

  1. creat the directory notebooks.
  2. add the bash script bash.sh with the following content.
FILES="$(find notebooks -maxdepth 1 -type f -name '*.ipynb')"
for f in $FILES
do
    nb2hugo $f --site-dir ./ --section posts
done

hugo  

Afterwards, I put all Jupyter notebooks under the notebooks directory, and run the script build.sh to build the blog. See this blog of the developer for more details. The above script is modified from the script in the demo.

In fact, this post is converted from notebook in this way. Let us display the following cells.

import numpy as np
import math
import matplotlib.pyplot as plt

x = np.linspace(0,2*math.pi)
print (x)
plt.plot(x, np.sin(x))
[0.         0.12822827 0.25645654 0.38468481 0.51291309 0.64114136
 0.76936963 0.8975979  1.02582617 1.15405444 1.28228272 1.41051099
 1.53873926 1.66696753 1.7951958  1.92342407 2.05165235 2.17988062
 2.30810889 2.43633716 2.56456543 2.6927937  2.82102197 2.94925025
 3.07747852 3.20570679 3.33393506 3.46216333 3.5903916  3.71861988
 3.84684815 3.97507642 4.10330469 4.23153296 4.35976123 4.48798951
 4.61621778 4.74444605 4.87267432 5.00090259 5.12913086 5.25735913
 5.38558741 5.51381568 5.64204395 5.77027222 5.89850049 6.02672876
 6.15495704 6.28318531]





[<matplotlib.lines.Line2D at 0x7feb9a086af0>]

png

Tags