Re: [Pyparsing] Reading n words
Brought to you by:
ptmcg
From: Paul M. <pt...@au...> - 2008-09-04 01:26:25
|
Andreas - Pyparsing includes a built-in helper method, called countedArray. Here is how you use it: from pyparsing import * counted_list_of_words = countedArray(Word(alphas)) tests = """\ 1 foo 2 foo baz 3 foo bar baz""".splitlines() for t in tests: print counted_list_of_words.parseString(t)[0] Prints: ['foo'] ['foo', 'baz'] ['foo', 'bar', 'baz'] countedArray(expr) matches Word(nums) + expr + expr + ... ("n" times, where n is the leading integer). Look at the pyparsing source code to see how countedArray uses a Forward expression that gets its content defined within a parse action attached to the leading integer. -- Paul -----Original Message----- From: pyp...@li... [mailto:pyp...@li...] On Behalf Of Andreas Matthias Sent: Wednesday, September 03, 2008 4:16 PM To: pyp...@li... Subject: [Pyparsing] Reading n words Hello, I'm trying to parse a string like '3 foo bar baz', where the number in the string specifies the number of the following words. Is there a more elegant way to achieve this than with the following code? Ciao Andreas from pyparsing import * def foo(st): p1 = Word(nums) n = p1.parseString(st)[0] p2 = Literal(n) + Word(alphas)*int(n) print p2.parseString(st) foo('1 foo') foo('2 foo baz') foo('3 foo bar baz') ------------------------------------------------------------------------- This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ _______________________________________________ Pyparsing-users mailing list Pyp...@li... https://lists.sourceforge.net/lists/listinfo/pyparsing-users |