保留文本结构信息 - pyparsing

时间:2016-08-07 00:00:34

标签: python python-2.7 parsing text-parsing pyparsing

使用pyparsing,有没有办法在递归下降过程中提取你所处的上下文。让我解释一下我的意思。我有以下代码:

import pyparsing as pp

openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}"))
ident = pp.Word(pp.alphanums + "_" + ".")
comment = pp.Literal("//") + pp.restOfLine
messageName = ident
messageKw = pp.Suppress(pp.Keyword("msg"))
text = pp.Word(pp.alphanums + "_" + "." + "-" + "+")
otherText = ~messageKw + pp.Suppress(text)
messageExpr = pp.Forward()
messageExpr << (messageKw + messageName + openBrace +
                pp.ZeroOrMore(otherText) + pp.ZeroOrMore(messageExpr) +
                pp.ZeroOrMore(otherText) + closeBrace).ignore(comment)
testStr = "msg msgName1 { some text msg msgName2 { some text } some text }"
print messageExpr.parseString(testStr)

产生此输出:['msgName1', 'msgName2']

在输出中,我想跟踪嵌入式匹配的结构。我的意思是,例如,我希望以下输出带有上面的测试字符串:['msgName1', 'msgName1.msgName2']来跟踪文本中的层次结构。但是,我是pyparsing的新手,还没有找到一种方法来提取&#34; msgName2&#34;嵌入在&#34; msgName1。&#34;

的结构中

有没有办法使用setParseAction()的{​​{1}}方法来执行此操作,或者使用结果命名?

有用的建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

感谢Paul McGuire的忠告。以下是我所做的补充/更改,解决了这个问题:

msgNameStack = []

def pushMsgName(str, loc, tokens):
    msgNameStack.append(tokens[0])
    tokens[0] = '.'.join(msgNameStack)

def popMsgName(str, loc, tokens):
    msgNameStack.pop()

closeBrace = pp.Suppress(pp.Literal("}")).setParseAction(popMsgName)
messageName = ident.setParseAction(pushMsgName)

这是完整的代码:

import pyparsing as pp

msgNameStack = []


def pushMsgName(str, loc, tokens):
    msgNameStack.append(tokens[0])
    tokens[0] = '.'.join(msgNameStack)


def popMsgName(str, loc, tokens):
    msgNameStack.pop()

openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}")).setParseAction(popMsgName)
ident = pp.Word(pp.alphanums + "_" + ".")
comment = pp.Literal("//") + pp.restOfLine
messageName = ident.setParseAction(pushMsgName)
messageKw = pp.Suppress(pp.Keyword("msg"))
text = pp.Word(pp.alphanums + "_" + "." + "-" + "+")
otherText = ~messageKw + pp.Suppress(text)
messageExpr = pp.Forward()
messageExpr << (messageKw + messageName + openBrace +
                pp.ZeroOrMore(otherText) + pp.ZeroOrMore(messageExpr) +
                pp.ZeroOrMore(otherText) + closeBrace).ignore(comment)

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