Saving text structure information - pyraring

Using pyparsing, there is a way to extract the context you are in during a recursive descent. Let me explain what I mean. I have the following code:

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)

which produces this conclusion: ['msgName1', 'msgName2']

In the output, I would like to track the structure of inline matches. I mean, for example, I would like to get the following result with the test line above: ['msgName1', 'msgName1.msgName2']to track the hierarchy in the text. However, I am new to pyparsing and have not yet found a way to extract the fact that " msgName2" is built into the structure " msgName1".

Is there a way to use the method setParseAction()to ParserElementdo this, or perhaps using naming?

Useful tips will be appreciated.

+4
1

. /, , :

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)
+2

Source: https://habr.com/ru/post/1650432/


All Articles