如何在IPython Notebook中显示LaTeX代码?


当前回答

这是当您想要控制文档序言时的另一种解决方案。编写整个文档,将其发送到system latex,将pdf转换为png,使用IPython。显示加载和显示。

import tempfile
import os.path
import subprocess
from IPython.display import Image, display

with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
    path = os.path.join(tmpdir, "document.tex")
    with open(path, 'w') as fp:
        fp.write(r"""
        \documentclass[12pt]{standalone}
        \begin{document}
        \LaTeX{}
        \end{document}
        """)
    subprocess.run(["lualatex", path], cwd=tmpdir)
    subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
    im = Image(filename=os.path.join(tmpdir, "document.png"))
    display(im)

其他回答

这是当您想要控制文档序言时的另一种解决方案。编写整个文档,将其发送到system latex,将pdf转换为png,使用IPython。显示加载和显示。

import tempfile
import os.path
import subprocess
from IPython.display import Image, display

with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
    path = os.path.join(tmpdir, "document.tex")
    with open(path, 'w') as fp:
        fp.write(r"""
        \documentclass[12pt]{standalone}
        \begin{document}
        \LaTeX{}
        \end{document}
        """)
    subprocess.run(["lualatex", path], cwd=tmpdir)
    subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
    im = Image(filename=os.path.join(tmpdir, "document.png"))
    display(im)

如果您的主要目标是做数学运算,那么SymPy提供了一种很好的方法来实现看起来很棒的函数乳胶表达式。

如果希望从笔记本代码单元中显示LaTeX方程,可以创建一个简单的包装器类,利用Jupyter笔记本丰富的显示表示。这个类应该有一个_repr_latex_方法(注意在开始和结束处有一个下划线,而不是其他特殊方法的双下划线)来输出LaTeX字符串。例如:

class LaTeXEquation:
    def __init__(self, eqntext):
        self.eqntext = eqntext

    def __repr__(self):
        return repr(self.eqntext)

    def _repr_latex_(self):
        """
        Special method for rich display of LaTeX formula.
        """

        # add $'s at start and end if not present
        if self.eqntext.strip()[0] != "$" and self.eqntext.strip()[-1] != "$":
            return "$" + self.eqntext + "$"
        else:
            return self.eqntext

myeqn = "x = y^2"

然后在代码单元格中,如果你这样做,例如,

LaTeXEquation(myeqn)

它将显示格式化的方程式。

minrk给出的答案(包括完整性)很好,但还有另一种方式我更喜欢。

通过在文本单元格中键入%% LaTeX作为第一行,还可以将整个单元格呈现为LaTeX。这很有用,如果你

想要更多的控制, 想要的不仅仅是数学环境, 或者如果你要在一个格子里写很多数学。

minrk的回答是:


IPython笔记本使用MathJax进行渲染 html/markdown中的LaTeX。只要把你的LaTeX数学放在$$中。 $$c = \√{a^2 + b^2}$$ 或者你也可以从Python中显示LaTeX / Math输出,如图所示 笔记本的结尾 旅游: IPython。display导入display, Math, Latex 显示器(数学(r 'F (k) = \ int_ {- \ infty} ^ {\ infty} f (x) e ^{2 \πk} dx '))

有一天我在使用colab时遇到了这个问题。我发现最省事的方法就是在打印之前运行这段代码。那么,一切都很有魅力。

from IPython.display import Math, HTML

def load_mathjax_in_cell_output():
  display(HTML("<script src='https://www.gstatic.com/external_hosted/"
               "mathjax/latest/MathJax.js?config=default'></script>"))
get_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)
import sympy as sp
sp.init_printing()

结果如下所示: