使用pyparsing(latex)解析嵌套组(带引号的字符串)

时间:2013-09-20 18:41:20

标签: python pyparsing

我想在LaTeX文件中解析可能嵌套的组:如下所示:

import pyparsing as pp
qs = pp.QuotedString(quoteChar='{', endQuoteChar='}')
s = r'''{ This is a \textbf{\texttt{example}} of \textit{some $\mb{y}$ text} to parse.}'''
print qs.parseString(s)

但这不可能是正确的(它停在第一个右大括号上)。输出是:

([' This is a \\textbf{\\texttt{example'], {})

我怎样才能得到一个我可以迭代的结果,我想这样的回报,如果我想要的只是小组:

{ This is a \textbf{\texttt{example}} of \textit{some $\mb{y}$ text} to parse.}
{\texttt{example}}
{example}
{some $\mb{y}$ text}
{y}

用例是测试LaTeX源文件是否存在常见的标记错误。

1 个答案:

答案 0 :(得分:2)

这里的关键是嵌套括号与其右括号正确匹配。你写的语法确实会停在第一个结束括号,而不是匹配的右括号。解决方案是定义一个语法,使新的开括号匹配为另一个部分。

import pyparsing as pp

allSections = []
def rememberSection(m):
    allSections.append(''.join(m))
other = pp.Word(pp.printables.replace('{','').replace('}','') + ' \t\r\n')
section = pp.Forward()
section << ('{' + pp.OneOrMore(other | section) + '}').setParseAction(rememberSection)

s = r'''{ This is a \textbf{\texttt{example}} of \textit{some $\mb{y}$ text} to parse.}'''
print section.parseString(s)
print allSections

这定义了允许在部分内部作为除括号或其他部分之外的所有内容。然后将每个支架与相应的闭合支撑相匹配。如果大括号不匹配,则会引发pyparsing.ParseException

通常,令牌都将作为令牌列表返回,每个令牌都匹配“{”,“}”或其他一系列非支撑字符。由于我们希望记住每个括号中的表达式,因此parseAction将它们添加到外部列表中。我不确定是否有任何更清晰的方法来处理它,但是这将构建包含所需组的allSections列表。

相关问题