代码之家  ›  专栏  ›  技术社区  ›  RSW

使用Python格式化LaTeX表达式

  •  0
  • RSW  · 技术社区  · 3 年前

    我有一个格式不好的LaTeX,需要以特定的方式格式化才能在Jupyter Notebook中正确渲染:

    # Supporting Libraries:
    from qiskit.visualization import array_to_latex
    from IPython.display import display, Markdown
    
    # Unsuitable LaTeX
    latex_baad =  '$QFT = \\frac{1}{\\sqrt{32}} \n\n\\begin{bmatrix}\n0  \\\\\n -1  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n \\tfrac{1}{\\sqrt{2}}(1 - i)  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n -0.92388 + 0.38268i  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n -0.19509 - 0.98079i  \\\\\n \\end{bmatrix}\n$'
    
    # Suitable LaTeX
    latex_good = r'$QFT =  \frac{1}{ \sqrt{32}}      \begin{bmatrix}  0  \\     -1          \end{bmatrix}    \otimes      \begin{bmatrix}  0       \\ \tfrac{1}{ \sqrt{2}}(1 - i)          \end{bmatrix}    \otimes      \begin{bmatrix}  0      \\ -0.92388 + 0.38268i          \end{bmatrix}    \otimes      \begin{bmatrix}  0      \\ -0.19509 - 0.98079i          \end{bmatrix}$'
    
    
    display(Markdown(latex_good))
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   RSW    3 年前

    这可以通过替换换行符来解决 \n 带有临时字符,例如。 ~ 不存在于 latex_baad

    
    latex_baad = latex_baad.replace("\n","~")
    latex_good = latex_baad.replace("~","")
    
    display(Markdown(latex_good))
    
    
        2
  •  1
  •   user11717481    3 年前

    使用 replace 为了将其修改到位,<你的铃声>。replace(‘要删除的子字符串’,‘要替换的子字符串‘)

    我建议大家“ \n\n “进入” \n “,然后全部” \n “进入 " "

    your_string.replace("\n\n","\n")
    your_string.replace("\n", " ")
    your_string.replace("////","//")
    

    对于raw(无法逃脱),我相信你只是在你的字符串前面加上 r' '

    比如:

    string = r'this will ignore escape characters \n\n'