【问题标题】:Custom sympy MathJax attributes in jupyterjupyter中的自定义sympy MathJax属性
【发布时间】:2019-09-27 18:22:21
【问题描述】:

我正在尝试在 Jupyter 下生成的 MathJax 中使用自定义属性制作 sympy 渲染表达式。如果我使用 IPython.display.HTML 显式渲染它,我可以让它工作,但是我希望将其设为 sympy 渲染表达式的默认方式。

from sympy.printing.mathml import MathMLPresentationPrinter
from sympy import init_printing,Symbol,Function
from sympy.abc import x,y,z
from IPython.display import HTML


class MyMathMLPresentationPrinter(MathMLPresentationPrinter):
    def _print(self,expr):
        res=super()._print(expr)
        res.attributes['myattrib']='myvalue'
        return(res)

    def doprint(self, expr):
        mathML = self._print(expr)
        unistr = mathML.toxml()
        xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
        res = xmlbstr.decode()
        return res


F=Function('F')
expr=F(x).diff(x)

我希望的结果可以使用(您需要使用 Firefox 中的 Inspector 或类似工具来查看)。

ml=MyMathMLPresentationPrinter()._print(expr).toxml()
HTML('<math>'+ml+'</math>')

我尝试执行以下操作,但这并没有解决问题。

def my_print(expr, **settings):
    ml= MyMathMLPresentationPrinter().doprint(expr)
    return ml
sympy.init_printing(pretty_printer=my_print,pretty_print=True,use_latex=False)

expr

关于如何进行这项工作的任何建议?

谢谢

【问题讨论】:

    标签: python sympy pretty-print


    【解决方案1】:

    如果其他人需要这个,下面会做我想做的事

    from sympy.printing.mathml import MathMLPresentationPrinter
    from sympy import init_printing,Symbol,Function
    from sympy.abc import x,y
    from IPython.display import HTML
    from sympy.core.basic import Basic
    
    class MyMathMLPresentationPrinter(MathMLPresentationPrinter):
        def _print(self,expr):
            res=super()._print(expr)
            res.attributes['sympyclass']=type(expr).__name__
            return(res)
    
        def _print_AppliedUndef(self, e):
            mrow = self.dom.createElement('mrow')
            x = self.dom.createElement('mi')
            x.appendChild(self.dom.createTextNode(e.__class__.__name__))
            y = self.dom.createElement('mfenced')
            for arg in e.args:
                y.appendChild(self._print(arg))
            mrow.appendChild(x)
            mrow.appendChild(y)
            return mrow
    
        def doprint(self, expr):
            mathML = self._print(expr)
            unistr = mathML.toxml()
            xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
            res = xmlbstr.decode()
            return res
    
    
    def basic_html(obj):
        ml=MyMathMLPresentationPrinter()._print(obj).toxml()
        return '<math>'+ml+'</math>'
    
    html_formatter = get_ipython().display_formatter.formatters['text/html']
    html_formatter.for_type(Basic, basic_html)
    
    init_printing()
    F=Function('F')
    expr=F(x).diff(x)
    expr
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 2014-09-10
      • 2017-10-08
      • 1970-01-01
      • 2012-02-15
      • 2011-03-27
      • 2011-01-24
      相关资源
      最近更新 更多