Jupyter笔记本:使用_repr_HTML_方法用HTML和数学显示类

2024-06-04 08:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写用于Jupyter笔记本的python类,这些类应该有漂亮的表示形式。为此,我定义了_repr_html_方法(可以由matplotlib动态生成embed graphics)。但有时我也想包括数学。比如说,

import pandas as pd
import IPython.display as idisp

class FooHtml:
    def __init__(self):
        self.df = pd.DataFrame({'alpha': [1.0, 2, 3], 'beta': [0.1, 0.2, 0.3]})

    def _repr_html_(self):
        math = idisp.Math(r'\alpha = \int f(\tau)\,d\tau')
        return (
            '<h3>FooHtml</h3>'  
            f'{self.df._repr_html_()}<br>\n'
            f'Explanation: {math}, where tau is the time.'
        )

FooHtml()

此单元格输入将生成以下输出:

Jupyter display

虽然display(math)显示了一个等式,但这并没有显示数学:

math formula

不呈现是因为str(math) == '<IPython.core.display ...>'将被解释为无效的HTML标记。问题是:如何实际呈现嵌入HTML表示中的数学。我找到了答案,但我在任何地方都找不到;我会把它贴出来作为答案


Tags: importselfdfdefhtmlasipythondisplay
2条回答

_repr_html_返回的HTML字符串可能在$$ ... $$$ ... $字符串中包含LaTeX格式的数学。虽然没有从_repr_html_的输出中解析其他标记格式,但实际解析了$分隔的数学:

class FooHtml:
    def __init__(self):
        self.df = pd.DataFrame({'alpha': [1.0, 2, 3], 'beta': [0.1, 0.2, 0.3]})

    def _repr_html_(self):
        math = idisp.Math(r'') 
        return (
            '<h3>FooHtml</h3>'
            f'{self.df._repr_html_()}<br>\n'
            r'Explanation: $$\alpha = \int f(\tau)\,d\tau,$$'
            r'where $\tau$ is the time.'
        )

FooHtml()

输出:

Jupyter display

或者,您可以创建一个_repr_markdown_方法。虽然DataFrame._repr_markdown_不存在,但可以在标记中嵌入HTML表:

class FooMarkdown:
    def __init__(self):
        self.df = pd.DataFrame({'alpha': [1.0, 2, 3], 'beta': [0.1, 0.2, 0.3]})

    def _repr_markdown_(self):
        return (
            '### FooMarkDown'
            f'{self.df._repr_html_()}<br>\n'
            r'Explanation: $$\alpha = \int f(\tau)\,d\tau$$ where $\tau$ is the time'
        )


FooMarkdown()

Jupyter display

这正是促使我创建jupydoc的原因,它还使用标记来统一图形、格式化文本和文本

有了机器,答案很简单:

from jupydoc import Publisher

class FooMarkdown(Publisher):
    def foo(self):
        r"""
        ### FooHTML
        
        {df}
        
        Explanation:
        
        $\alpha = \int f(\tau)\,d\tau$
        
        where $\tau$ is the time.
        """
        df = pd.DataFrame({'alpha': [1.0, 2, 3], 'beta': [0.1, 0.2, 0.3]})
        self.publishme()
FooMarkdown().foo()

导致:

enter image description here

相关问题 更多 >