如何在IPython Notebook中显示LaTeX代码?
当前回答
我开发了pretty typy,它提供了一种打印方程的好方法。不幸的是,它不是高性能的,需要测试。
例子:
当然,sympy是一个很好的替代方案,尽管prettyPy不允许计算表达式,变量初始化是不需要的。
其他回答
您可以选择一个要降价的单元格,然后编写由mathjax解释的latex代码,就像上面提到的应答器之一一样。
另外,iPython笔记本教程的Latex部分很好地解释了这一点。
你可以这样做:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
或者这样做:
%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
更多信息在此链接
如果您的主要目标是做数学运算,那么SymPy提供了一种很好的方法来实现看起来很棒的函数乳胶表达式。
这是当您想要控制文档序言时的另一种解决方案。编写整个文档,将其发送到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)
这是在我刚刚做的搜索中出现的,通过更多的搜索发现了一个更好的解决方案,IPython笔记本现在有一个%%乳胶魔法,使整个细胞乳胶没有$$包装每行。
关于富显示系统,请参考笔记本手册
如果希望从笔记本代码单元中显示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)
它将显示格式化的方程式。
推荐文章
- 检查pandas数据框架索引中是否存在值
- 在LaTeX中突出显示源代码
- 如何将LaTeX与Markdown混合?
- Ipython笔记本清除单元格输出代码
- 在LaTeX中出现“Missing $ inserted”错误
- tqdm在Jupyter笔记本重复打印新的进度条
- 乳胶渲染在README。md在Github上
- 在LaTeX中引用一个表
- 折叠单元在jupyter笔记本
- 如何知道哪个Python在Jupyter笔记本上运行?
- 使用Python 3在Jupyter Notebook中使用相对导入从位于另一个目录中的模块导入本地函数
- 如何嵌入HTML到IPython输出?
- 如何在Latex中编写url ?
- 使用pandoc从Markdown转换为PDF时设置空白大小
- Python和IPython的区别是什么?