Sorry for the newbie question but this problem has been driving me nuts and many hours of searching haven't found me a solution.
I have a router config input file which looks something like:
groups {
...some nested info...
}
some text....
system {
...some nested info...
}
chassis {
...some nested info...
}
Now using pyparsing and nestedExpr, I can parse the first part 'groups' and I get a set of lists within lists which are perfect, but I can't continue on to 'system' or 'chassis'.
Ideally, I'd like to start at 'chassis' and just get the list of lists from that section and nothing else.
Is there a way of getting pyparsing and nestedExpr to either do the whole file or start at a certain point?
My current code is pretty simple, ideally how do I get it to start from 'chassis':
from pyparsing import *
with open('newfile.txt') as routerFile:
test = routerFile.read()
expr = Word(alphas) + nestedExpr('{','}')
print expr.parseString(test)
You have a couple of options when you want to parse only selected bits of a larger text.
One is to use pyparsing's SkipTo
class.
from pyparsing import Word, SkipTo
text = "AAA stuff I dont care about BBB more junk"
part1 = Word("A")
part2 = Word("B")
parser = part1 + SkipTo(part2) + part2
print(parser.parseString(text).asList())
prints
['AAA', 'stuff I dont care about ', 'BBB']
If you really don't want that intervening stuff, use SkipTo(part2).suppress()
.
Another way to pick through text is to use scanString or searchString instead of parseString, as described in this answer.