{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Easily Creating Strings with Templating \n", "\n", "The CDAT software was developed by LLNL. This tutorial was written by Charles Doutriaux. This work was performed under the auspices of the U.S. Department of Energy by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.\n", "\n", "\n", "\n", "[Download the Jupyter Notebook](EasilyCreatingStringsWithTemplating.ipynb)" ] }, { "cell_type": "markdown", "metadata": { "toc": true }, "source": [ "

Table of Contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Define Your String Template\n", "\n", "[Back to Top](#top)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import genutil\n", "# Define your string template\n", "file_template = \"%(path)/%(variable).%(model).nc\"\n", "# Create a StringConstructor object\n", "S = genutil.StringConstructor(file_template)\n", "# Fill the StringConstructor with the values for each key\n", "S.path = \"blah\"\n", "S.variable = \"tas\"\n", "S.model= \"CNRM\"\n", "my_path = S()\n", "print(\"My file path is:\",my_path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can also pass keys at retrieval time\n", "print(\"My file path for variable 'pr' is:\",S(variable=\"pr\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can easily loop through keys like this:\n", "for model in [\"modelA\",\"modelB\",\"modelC\"]:\n", " for variable in [\"tas\",\"pr\",\"zg\",\"u\",\"v\"]:\n", " S.model = model\n", " path = S(variable=variable)\n", " print(\"PATH IS:\",path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# in some case you can even reverse ingeneer\n", "print(\"key/values pairs:\",S.reverse(path))" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }