Expand variables in Markdown cells of ipython-notebook

天涯浪子 提交于 2019-12-10 04:06:45

问题


Inside a markdown cell in an ipython-notebook I'd like to be able to expand variables automatically. Can this be done?

As an example, consider the following code

from IPython.core.display import HTML
from markdown import markdown

base_url = "https://stackoverflow.com/"
markdown_string = "Two categories at [stackoverflow]({0}) are "\
                  "[ipython-notebook]({0}questions/tagged/ipython-notebook) and "\
                  "[matplotlib]({0}questions/tagged/matplotlib).".format(base_url)
HTML("<p>{}</p>".format(markdown(markdown_string)))

This produces the output cell with the links correct, all relative to base_url, as

Two categories at stackoverflow are ipython-notebook and matplotlib.

What I would like is to be able to directly type the markdown into the cell, referencing a pre-defined variable. Is this possible?


回答1:


Although it's not possible yet to do with a real Markdown cell, you can easily create a magic to get the same effect.

from __future__ import absolute_import
from IPython.core.getipython import get_ipython
from IPython.core.magic import (Magics, magics_class,  cell_magic)

@magics_class
class MarkdownMagics(Magics):

    @cell_magic
    def markdown(self, line, cell):
        from IPython.core.display import HTML
        from markdown import markdown

        vars = line.split()

        d = {}
        for k, v in self.shell.user_ns.items():
            if k in vars:
                d[k] = v

        return HTML("<p>{}</p>".format(markdown(cell.format(**d))))

get_ipython().register_magics(MarkdownMagics)

Set some Variables

foo = 1
bar = 2

Then call the magic, with arguments being the variables you want to take from the namespace.

%%markdown foo bar

Substitute _{foo}_ and *{bar}*



回答2:


As @Jakob answered in the comments, the easiest way to accompish this is to install the python-markdown IPython notebook extension, as described on the wiki page.

You can then access your variables in markdown by surrounding them with curly brackets:

Python cell:

x = 1000

Markdown cell:

Insert variable contents here -> {{x}}.

The markdown cell gets parsed as:

Insert variable contents here -> 1000.


来源:https://stackoverflow.com/questions/21364102/expand-variables-in-markdown-cells-of-ipython-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!