Hi Paul and everyone else,
I ran the script and here's what I got:
Python version: 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)]
pyparsing version: 1.3
'abc def' -> ['abc', 'def']
'abc' -> ['abc']
It seems to work fine.
I figured out what my problem was: my earlier description was
erroneous. The type for Results2 was actually 'str', not
'pyparsing.ParseResults' as I had mentioned. (I was typing from memory
-- I didn't actually run my code.... sorry, my bad).
It seems that the way I was parsing it, I sometimes got
pyparsing.parseResults lists, and sometimes got *strings* (not
actually single-element lists as I thought).
I had expected pyparsing results to always return lists, I guess with
my token description below, it doesn't. Here's the bit of code I've
wrote:
from pyparsing import *
unit = Word(alphanums)
section = unit + Literal(':').suppress()
line = ~section + Combine(unit + SkipTo(Literal(';'), include=True))
block = ZeroOrMore(line)
file = Dict(ZeroOrMore(Group(section + block)))
Results = dict(file.parseString(MyFileString)
Where MyFileStrings (the string I want to parse) is something like
this:
var:
x, y, z;
constraints:
x <= 1;
y <= 2;
z <= 3;
And the results I'd get would be something like this:
Results
{'var': 'x, y, z;', 'constraints': (['x <= 1', 'y <= 2', 'z <= 3'],
{})}
So going along Jeff Epler's line of thinking, I wrote a convenience
function:
def convertToList(input):
if type(input) == str:
output = [input]
else:
output = input
return output
So when I iterate through the keys of the Results dictionary, I just
have to convertToList(value) and I will always get a list.
Thanks for your feedback, everyone!
(and embarassingly, I just realized I was talking to the author of
pyparsing. Thanks for pyparsing, Paul! I'm using it to write a
mini-language for defining process control models used in chemical
engineering, and it has really given me a lot of leverage in terms of
churning actual working code out in minimal time. I was thinking of
doing it the lex/yacc way at first, but pyparsing is so much easier.)