Вопрос

I am trying to use pyparsing to parse a configuration file of following form

x = "/user/test"
y = 3

Here is my code snippet

ParserElement.defaultWhitespaceChars = (" \t")
END = StringEnd()
NL = LineEnd().suppress()
assignment = Literal('=')

key_str = CharsNotIn("=")
value_str = Group(~assignment + restOfLine)

line = Group(key_str + assignment + value_str)
lines = ZeroOrMore(line)
lines.ignore(NL)

text = """
y = 3
x = 2
"""

The output that I get from parseFile tells me it is parsing the first line only. Can anybody please help me find out what I am doing wrong?

Это было полезно?

Решение

It looks like you are on the right track. Maybe you are doing something wrong when you acutally pass the text to the grammar. Adding the following line in your code

print lines.parseString(text)

Gives the expected output

[['y ', '=', [' 3']], ['x ', '=', [' 2']]]

As an aside, normally you don't want to keep the whitespace when parsing. The tokens are usually the only thing that matters. This is how I would parse your example:

EOL = LineEnd().suppress()
EQ  = Literal("=").suppress()
val = Word(alphanums)
line = Group(val('key') + EQ + val('val') + EOL)
grammar = OneOrMore(line)

for x in grammar.parseString(text):
    print x.dump()

The output in this case is much nicer

['y', '3']
- key: y
- val: 3
['x', '2']
- key: x
- val: 2
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top