From 10f788282c13da622318a9f88d605add655782f8 Mon Sep 17 00:00:00 2001 From: Jake VanderPlas Date: Fri, 18 Nov 2016 08:26:56 -0800 Subject: [PATCH] create tool for adding book info --- tools/README.md | 4 +++- tools/add_book_info.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 tools/add_book_info.py diff --git a/tools/README.md b/tools/README.md index ea72dfbf0..a4cd76d77 100644 --- a/tools/README.md +++ b/tools/README.md @@ -4,4 +4,6 @@ These are tools for managing the notebooks in this repository. - ``generate_contents.py``: this will generate a markdown table of contents for use in the README and in the Index.ipynb notebook -- ``add_navigation.py``: this script adds navigation links at the top and bottom of each notebook. \ No newline at end of file +- ``add_navigation.py``: this script adds navigation links at the top and bottom of each notebook. + +- ``add_book_info.py``: this script adds book information to the top of each notebook. \ No newline at end of file diff --git a/tools/add_book_info.py b/tools/add_book_info.py new file mode 100644 index 000000000..7e8f0318c --- /dev/null +++ b/tools/add_book_info.py @@ -0,0 +1,36 @@ +import os + +import nbformat +from nbformat.v4.nbbase import new_markdown_cell + +from generate_contents import iter_notebooks, NOTEBOOK_DIR + + +BOOK_COMMENT = "" + + +BOOK_INFO = BOOK_COMMENT + """ + +*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).* + +*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please support the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*""" + + +def add_book_info(): + for nb_name in iter_notebooks(): + nb_file = os.path.join(NOTEBOOK_DIR, nb_name) + nb = nbformat.read(nb_file, as_version=4) + + is_comment = lambda cell: cell.source.startswith(BOOK_COMMENT) + + if is_comment(nb.cells[0]): + print('- amending comment for {0}'.format(nb_name)) + nb.cells[0].source = BOOK_INFO + else: + print('- inserting comment for {0}'.format(nb_name)) + nb.cells.insert(0, new_markdown_cell(BOOK_INFO)) + nbformat.write(nb, nb_file) + + +if __name__ == '__main__': + add_book_info()