In your case, you can append to the ParseResults that is passed in by creating a small ParseResults containing "1" and adding it to t:
t += ParseResults("1")
Unfortunately, this won't work as a lambda - you could try
lambda s, l, t: t.__iadd__(ParseResults("1"))
You might also rethink your parser a bit, to take advantage of the Optional class. Think of your trailing digit as an optional element, for which you can define a default value to provide in case the element is missing. I think you can define what you want with just:
>>> letter = Word(alphas, exact = 1) >>>
digit = Word(nums, exact = 1) >>>
teststring = "a2 b5 c9 d e z" >>>
letter_and_digit = Combine(letter + Optional(digit,
default = "1")) >>>
print(sum(letter_and_digit.searchString(teststring)))['a2', 'b5', 'c9', 'd1', 'e1', 'z1']
The parsed tokens are passed to the parse action as ParseResults. They can be modified in place using list-style append, extend, and pop operations to update the parsed list elements; and with dictionary-style item set and del operations to add, update, or remove any named results. If the tokens are modified in place, it is not necessary to return them with a return statement.,The optional aslist argument when set to True will return the parsed tokens as a Python list instead of a pyparsing ParseResults.,The optional asdict argument when set to True will return the parsed tokens as a Python dict instead of a pyparsing ParseResults.,Convenience wrapper assert to test a parser element and input string, and assert that the resulting ParseResults.asList() is equal to the expected_list.
from pyparsing import Word, alphas # define grammar of a greeting greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print(hello, "->", greet.parse_string(hello))
Hello, World!- > ['Hello', ',', 'World', '!']
integer = Word(nums) name_expr = Word(alphas)[1, ...] expr = And([integer("id"), name_expr("name"), integer("age")]) # more easily written as: expr = integer("id") + name_expr("name") + integer("age")
test = '' '\ AAA this line AAA and this line AAA but not this one B AAA and definitely not this one '' ' for t in (AtLineStart('AAA') + rest_of_line).search_string(test): print(t)
['AAA', ' this line']
['AAA', ' and this line']
AtStringStart(Word(nums)).parse_string("123")
# prints["123"]
AtStringStart(Word(nums)).parse_string(" 123")
# raises ParseException
Extension to scanString, to modify matching text with modified tokens that may be returned from a parse action. To use transformString, define a grammar and attach a parse action to it that modifies the returned token list. Invoking transformString() on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. transformString() returns the resulting transformed string.,Another extension to scanString, simplifying the access to the tokens found to match the given parse expression. May be called with optional maxMatches argument, to clip searching after 'n' matches are found.,Disables the skipping of whitespace before matching the characters in the ParserElement's defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.,Overrides default behavior to expand <TAB>s to spaces before parsing the input string. Must be called before parseString when the input grammar contains elements that match <TAB> characters.
Example:
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
Example:
# default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # - > ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # - > ['1999', '12', '31']
Example:
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints:
[5120, 100, 655360, 268435456]
Equivalent form of expr.copy()
is just
expr()
:
integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M")
Example:
Word(nums).parseString("ABC") # - > Exception: Expected W: (0123...)(at char 0), (line: 1, col: 1)
Word(nums).setName("integer").parseString("ABC") # - > Exception: Expected integer(at char 0), (line: 1, col: 1)
Example:
date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
Example:
integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # - > ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # - > [1999, '/', 12, '/', 31]