首页 > 解决方案 > pylatexen 无法分割段落

问题描述

我正在使用pylatexenc. 我对这个包没有经验,在这里找到了。

我有这个简单的 Latex 文档:

\documentclass{article}

\begin{document}
\title{This is my Latex document}
\author{Gordon Shumway}
\maketitle

\section{Introduction}

First paragraph.

This is a second paragraph in the first section.

\section{Second section}

Many times we have equations like this one 
\begin{equation}
\left(\gamma^{\mu}p_{\mu}-m\right)\left|\psi\right\rangle =0\label{Equation: Dirac}
\end{equation}
 and inline math such as $\psi$. And I can insert a reference to~(\ref{Equation: Dirac}).
\end{document}

可以看出,第一节有两段。pylatexenc如果我使用以下代码解析文档

from pylatexenc.latexwalker import LatexWalker

with open('latex_document.tex', 'r') as file:
    latex_file_str = file.read()

w = LatexWalker(latex_file_str)
nodelist,_,_ = w.get_latex_nodes(pos=0)

document = None
for node in nodelist:
    if hasattr(node, 'environmentname'):
        if node.environmentname == 'document':
            document = node

for node in document.nodelist:
    print(node, end=4*'\n')
    
document_title = None
for node in document.nodelist:
    if hasattr(node, 'macroname'):
        if node.macroname=='title':
            document_title = node
print(f'Title = {document_title.nodeargd.argnlist[0].nodelist[0].chars}')

但是,这两段被解析为一个元素:

Bla bla bla...
LatexCharsNode(parsing_state=<parsing state 140254491546672>, pos=134, len=70, chars='\n\nFirst paragraph.\n\nThis is a second paragraph in the first section.\n\n')
Bla bla bla...

难道我做错了什么?这是可以预料的吗?这是一个限制pylatexenc吗?

标签: pythonparsinglatex

解决方案


如您所述,pylatexenc目前不拆分段落。一个想法是将字符声明\n\n为“特殊乳胶”(参见,例如此处),但在内部pylatexenc特别对待空格,这个想法不起作用。您可以在github上发布功能请求或提交拉取请求 :)


推荐阅读