【问题标题】:parsing nested groups (quoted strings) with pyparsing (latex)使用 pyparsing (latex) 解析嵌套组(引用的字符串)
【发布时间】:2013-09-23 05:23:58
【问题描述】:

我想解析 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 源文件的常见标记错误。

【问题讨论】:

  • 看看 pyparsing 的 nestedExpr 是否比 QuotedString 更好。

标签: python pyparsing


【解决方案1】:

这里的关键是嵌套括号以正确匹配它们的右括号。您编写的语法确实会停在第一个右括号,而不是匹配的右括号。解决方案是定义一个语法,使新的左括号匹配为另一个部分。

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 列表。

【讨论】:

  • 善用 Forward 来定义递归解析表达式。最近发布的 pyparsing 为 Word 添加了一个参数,以简化“除 x 之外的所有可打印文件”的操作 - Word(printables, excludeChars="{}")
猜你喜欢
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多