notebook的Markdown单元格中展开变量

notebook的Markdown单元格中展开变量

本文介绍了在ipython-notebook的Markdown单元格中展开变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ipython笔记本的markdown单元格内,我希望能够自动扩展变量.能做到吗?

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)))

这将产生具有正确链接的输出单元,所有链接都相对于base_url,如

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

我想要的是能够直接引用单元格中的markdown,并引用预定义的变量.这可能吗?

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

推荐答案

尽管尚无法使用真正的Markdown单元,但您可以轻松创建魔术来获得相同的效果.

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)

设置一些变量

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}*

这篇关于在ipython-notebook的Markdown单元格中展开变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:23