【问题标题】:preserving text structure information - pyparsing保存文本结构信息 - pyparsing
【发布时间】:2016-08-07 00:00:34
【问题描述】:

使用 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 的新手,还没有找到一种方法来提取“msgName2”嵌入在“msgName1”的结构中这一事实。

有没有办法使用ParserElementsetParseAction() 方法来执行此操作,或者使用结果命名?

我们将不胜感激。

【问题讨论】:

  • 将解析操作附加到 messageName 以将名称推送到外部堆栈,并将解析操作附加到 closeBrace 以将姓氏从堆栈中弹出。在第一个解析动作中,将当前名称压入堆栈后,您可以将输入标记中的名称替换为tokens[0] = '.'.join(stack)

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


【解决方案1】:

感谢 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)

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多