3

我无法让 setResultsName 在此脚本中为我工作,即使在尝试模拟给出的示例时也是如此。我查看了文档,查阅了作者的书,并查看了论坛示例。我尝试了几种变化,坦率地说我有点难过,尽管我确信我做错了一些愚蠢的事情,因为我在这方面不是很有经验。

from pyparsing import *

lineId = Word(nums)
topicString = Word(alphanums+'-'+' '+"'")
expr = Forward()
full_entry = Group(lineId('responsenumber') + expr)

def new_line():
    return '\n' + lineId.responsenumber # <-- here is the line that causes the error

expr << topicString + Optional(nestedExpr(content=delimitedList(expr))) + Optional((Literal(';').setParseAction(new_line) + expr))


for line in input:
    inputParseResults = delimitedList(full_entry).parseString(line).asList()
    print inputParseResults

这部分代码试图做的是接受这个输入:

1768    dummy data; things
27483   other things

让它在分号处换行,再次附加 lineId,然后重新关联它,就像你在这一行看到的那样:

1768    dummy data
1768    things
27483   other things

还有其他代码来处理我未在此处显示的输出格式;我的主要障碍是换行 + lineId,我想如果我能让 setResultsName 工作,我可能会被设置。

4

2 回答 2

1

使用setParseActionforward都是让我头疼的东西(这就是我知道下次看代码时代码将无法阅读的方式)。

对于您所描述的, delimitedList 是一个不错的选择。除非您真的需要其他魔法的解析操作,否则如何:

from pyparsing import *

topicParser = Word(nums)("line") + \
              delimitedList(Word(alphanums+'-'+' '+"'"),';')("list")

for line in input:
    topics = topicParser.parseString(line)
    lineid = topics['line']
    for topic in topics['list']:
        print "{0} {1}".format(lineid,topic)
于 2012-04-27T22:34:06.353 回答
1

像这样将解析的标记传递到您的解析操作中,并根据标记访问结果名称,而不是针对解析器表达式:

def new_line(tokens): 
    return '\n' + tokens.responsenumber
于 2012-04-27T21:51:20.863 回答