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


当前回答

有一天我在使用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()

结果如下所示:

其他回答

这是当您想要控制文档序言时的另一种解决方案。编写整个文档,将其发送到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)

我开发了pretty typy,它提供了一种打印方程的好方法。不幸的是,它不是高性能的,需要测试。

例子:

当然,sympy是一个很好的替代方案,尽管prettyPy不允许计算表达式,变量初始化是不需要的。

IPython笔记本使用MathJax在html/markdown中渲染LaTeX。只要把你的LaTeX数学放在$$中。

$$c = \sqrt{a^2 + b^2}$$

或者你可以从Python中显示LaTeX / Math输出,就像在笔记本之旅结束时看到的那样:

from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))

Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/README.md and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here: https://rawgit.com/jfbercher/latex_envs/master/doc/latex_env_doc.html

\section{First section}
\textbf{Hello}
$
\begin{equation} 
c = \sqrt{a^2 + b^2}
\end{equation}
$
\begin{itemize}
\item First item
\item Second item
\end{itemize}
\textbf{World}

如你所见,我仍然无法使用uspackage。但也许将来会有所改进。

这是在我刚刚做的搜索中出现的,通过更多的搜索发现了一个更好的解决方案,IPython笔记本现在有一个%%乳胶魔法,使整个细胞乳胶没有$$包装每行。

关于富显示系统,请参考笔记本手册