pyparsing 删除一些文本以及如何使用空格捕获文本

pyparsing removing some text and how to capture text with whitespace

我刚开始使用 pyparsing (python 2.7),对这段代码有几个问题:

import pyparsing as pp

openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}"))
ident = pp.Word(pp.alphanums + "_" + ".")
otherStuff = pp.Suppress(pp.Word(pp.alphanums + "_" + "." + "-" + "+"))
comment = pp.Literal("//") + pp.restOfLine
messageName = ident
messageKw = pp.Suppress("msg")
messageExpr = pp.Forward()
messageExpr << (messageKw + messageName + openBrace +
                pp.Optional(otherStuff) + pp.ZeroOrMore(messageExpr) +
                pp.Optional(otherStuff) + closeBrace).ignore(comment)

print messageExpr.parseString("msg msgName1 { msg msgName2 { some text } }")

我真的不明白为什么它会删除内部 msgName2 中的文本 "msg"。输出是: ['msgName1', 'Name2'] 但我预计: ['msgName1', 'msgName2']

此外,我想知道如何捕获所有其他文本 ("some text"),包括大括号之间的空格。

提前致谢

回答您的第一个问题:

>>> import pyparsing as pp
>>> 
>>> openBrace = pp.Suppress(pp.Literal("{"))
>>> closeBrace = pp.Suppress(pp.Literal("}"))
>>> ident = pp.Word(pp.alphanums + "_" + ".")
>>> otherStuff = pp.Suppress(pp.Word(pp.alphanums + "_" + "." + "-" + "+"))
>>> comment = pp.Literal("//") + pp.restOfLine
>>> messageName = ident
>>> messageKw = pp.Suppress("msg")
>>> messageExpr = pp.Forward()
>>> messageExpr << (messageKw + messageName + openBrace +
...                 pp.ZeroOrMore(messageExpr) + pp.ZeroOrMore(otherStuff) +
...             closeBrace).ignore(comment)
Forward: ...
>>> 
>>> print messageExpr.parseString("msg msgName1 { msg msgName2 { some text } }")
['msgName1', 'msgName2']

几点:

  1. messageKw 应该使用 pyparsing 关键字 class 来定义。现在你只是匹配文字 "msg",所以即使它是 "msgName2" 的前导部分,它也会匹配。将其更改为:

    messageKw = pp.Suppress(pp.Keyword("msg"))
    
  2. otherStuff 是一个非常贪婪的匹配器,甚至会匹配前导 "msg" 关键字,这会搞砸你的嵌套匹配。您需要添加的只是 otherStuff 中的前瞻性,以确保您要匹配的不是 'msg' 关键字:

    otherStuff = ~messageKw + pp.Suppress(pp.Word(pp.alphanums + "_" + "." + "-" + "+"))
    

我认为有了这些改变,你应该能够取得更大的进步。

顺便说一下,恭喜你编写了一个递归解析器(使用 Forward class)。这通常是一个更高级的解析主题。