OpenQuizz
Une application de gestion des contenus pédagogiques
ParseResults Class Reference
Inheritance diagram for ParseResults:
Collaboration diagram for ParseResults:

Public Member Functions

def __new__ (cls, toklist=None, name=None, asList=True, modal=True)
 
def __init__ (self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance)
 
def __getitem__ (self, i)
 
def __setitem__ (self, k, v, isinstance=isinstance)
 
def __delitem__ (self, i)
 
def __contains__ (self, k)
 
def __len__ (self)
 
def __bool__ (self)
 
def __iter__ (self)
 
def __reversed__ (self)
 
def keys (self)
 
def values (self)
 
def items (self)
 
def haskeys (self)
 
def pop (self, *args, **kwargs)
 
def get (self, key, defaultValue=None)
 
def insert (self, index, insStr)
 
def append (self, item)
 
def extend (self, itemseq)
 
def clear (self)
 
def __getattr__ (self, name)
 
def __add__ (self, other)
 
def __iadd__ (self, other)
 
def __radd__ (self, other)
 
def __repr__ (self)
 
def __str__ (self)
 
def asList (self)
 
def asDict (self)
 
def copy (self)
 
def asXML (self, doctag=None, namedItemsOnly=False, indent="", formatted=True)
 
def getName (self)
 
def dump (self, indent='', full=True, include_list=True, _depth=0)
 
def pprint (self, *args, **kwargs)
 
def __getstate__ (self)
 
def __setstate__ (self, state)
 
def __getnewargs__ (self)
 
def __dir__ (self)
 
def from_dict (cls, other, name=None)
 

Static Public Attributes

 keys
 
 values
 
 items
 
 iterkeys
 
 itervalues
 
 iteritems
 

Detailed Description

Structured parse results, to provide multiple means of access to
the parsed data:

   - as a list (``len(results)``)
   - by list index (``results[0], results[1]``, etc.)
   - by attribute (``results.<resultsName>`` - see :class:`ParserElement.setResultsName`)

Example::

    integer = Word(nums)
    date_str = (integer.setResultsName("year") + '/'
                    + integer.setResultsName("month") + '/'
                    + integer.setResultsName("day"))
    # equivalent form:
    # date_str = integer("year") + '/' + integer("month") + '/' + integer("day")

    # parseString returns a ParseResults object
    result = date_str.parseString("1999/12/31")

    def test(s, fn=repr):
        print("%s -> %s" % (s, fn(eval(s))))
    test("list(result)")
    test("result[0]")
    test("result['month']")
    test("result.day")
    test("'month' in result")
    test("'minutes' in result")
    test("result.dump()", str)

prints::

    list(result) -> ['1999', '/', '12', '/', '31']
    result[0] -> '1999'
    result['month'] -> '12'
    result.day -> '31'
    'month' in result -> True
    'minutes' in result -> False
    result.dump() -> ['1999', '/', '12', '/', '31']
    - day: 31
    - month: 12
    - year: 1999

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
  toklist = None,
  name = None,
  asList = True,
  modal = True,
  isinstance = isinstance 
)

Member Function Documentation

◆ __add__()

def __add__ (   self,
  other 
)

◆ __bool__()

def __bool__ (   self)

◆ __contains__()

def __contains__ (   self,
  k 
)

◆ __delitem__()

def __delitem__ (   self,
  i 
)

◆ __dir__()

def __dir__ (   self)

◆ __getattr__()

def __getattr__ (   self,
  name 
)

◆ __getitem__()

def __getitem__ (   self,
  i 
)

◆ __getnewargs__()

def __getnewargs__ (   self)

◆ __getstate__()

def __getstate__ (   self)

◆ __iadd__()

def __iadd__ (   self,
  other 
)

◆ __iter__()

def __iter__ (   self)

◆ __len__()

def __len__ (   self)

◆ __new__()

def __new__ (   cls,
  toklist = None,
  name = None,
  asList = True,
  modal = True 
)

◆ __radd__()

def __radd__ (   self,
  other 
)

◆ __repr__()

def __repr__ (   self)

◆ __reversed__()

def __reversed__ (   self)

◆ __setitem__()

def __setitem__ (   self,
  k,
  v,
  isinstance = isinstance 
)

◆ __setstate__()

def __setstate__ (   self,
  state 
)

◆ __str__()

def __str__ (   self)

◆ append()

def append (   self,
  item 
)
Add single element to end of ParseResults list of elements.

Example::

    print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']

    # use a parse action to compute the sum of the parsed integers, and add it to the end
    def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
    print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]

◆ asDict()

def asDict (   self)
Returns the named parse results as a nested dictionary.

Example::

    integer = Word(nums)
    date_str = integer("year") + '/' + integer("month") + '/' + integer("day")

    result = date_str.parseString('12/31/1999')
    print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})

    result_dict = result.asDict()
    print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}

    # even though a ParseResults supports dict-like access, sometime you just need to have a dict
    import json
    print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
    print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}

◆ asList()

def asList (   self)
Returns the parse results as a nested list of matching tokens, all converted to strings.

Example::

    patt = OneOrMore(Word(alphas))
    result = patt.parseString("sldkj lsdkj sldkj")
    # even though the result prints in string-like form, it is actually a pyparsing ParseResults
    print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']

    # Use asList() to create an actual list
    result_list = result.asList()
    print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']

◆ asXML()

def asXML (   self,
  doctag = None,
  namedItemsOnly = False,
  indent = "",
  formatted = True 
)
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.

◆ clear()

def clear (   self)
Clear all elements and results names.

◆ copy()

def copy (   self)
Returns a new copy of a :class:`ParseResults` object.

◆ dump()

def dump (   self,
  indent = '',
  full = True,
  include_list = True,
  _depth = 0 
)
Diagnostic method for listing out the contents of
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
that this string can be embedded in a nested display of other data.

Example::

    integer = Word(nums)
    date_str = integer("year") + '/' + integer("month") + '/' + integer("day")

    result = date_str.parseString('12/31/1999')
    print(result.dump())

prints::

    ['12', '/', '31', '/', '1999']
    - day: 1999
    - month: 31
    - year: 12

◆ extend()

def extend (   self,
  itemseq 
)
Add sequence of elements to end of ParseResults list of elements.

Example::

    patt = OneOrMore(Word(alphas))

    # use a parse action to append the reverse of the matched strings, to make a palindrome
    def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
    print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'

◆ from_dict()

def from_dict (   cls,
  other,
  name = None 
)
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned

◆ get()

def get (   self,
  key,
  defaultValue = None 
)
Returns named result matching the given key, or if there is no
such name, then returns the given ``defaultValue`` or ``None`` if no
``defaultValue`` is specified.

Similar to ``dict.get()``.

Example::

    integer = Word(nums)
    date_str = integer("year") + '/' + integer("month") + '/' + integer("day")

    result = date_str.parseString("1999/12/31")
    print(result.get("year")) # -> '1999'
    print(result.get("hour", "not specified")) # -> 'not specified'
    print(result.get("hour")) # -> None

◆ getName()

def getName (   self)
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.

Example::

    integer = Word(nums)
    ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
    house_number_expr = Suppress('#') + Word(nums, alphanums)
    user_data = (Group(house_number_expr)("house_number")
        | Group(ssn_expr)("ssn")
        | Group(integer)("age"))
    user_info = OneOrMore(user_data)

    result = user_info.parseString("22 111-22-3333 #221B")
    for item in result:
print(item.getName(), ':', item[0])

prints::

    age : 22
    ssn : 111-22-3333
    house_number : 221B

◆ haskeys()

def haskeys (   self)
Since keys() returns an iterator, this method is helpful in bypassing
   code that looks for the existence of any defined results names.

◆ insert()

def insert (   self,
  index,
  insStr 
)
Inserts new element at location index in the list of parsed tokens.

Similar to ``list.insert()``.

Example::

    print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']

    # use a parse action to insert the parse location in the front of the parsed results
    def insert_locn(locn, tokens):
tokens.insert(0, locn)
    print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']

◆ items()

def items (   self)
Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).

◆ keys()

def keys (   self)
Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).

◆ pop()

def pop (   self,
args,
**  kwargs 
)
Removes and returns item at specified index (default= ``last``).
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
passed no argument or an integer argument, it will use ``list``
semantics and pop tokens from the list of parsed tokens. If passed
a non-integer argument (most likely a string), it will use ``dict``
semantics and pop the corresponding value from any defined results
names. A second default return value argument is supported, just as in
``dict.pop()``.

Example::

    def remove_first(tokens):
tokens.pop(0)
    print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
    print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']

    label = Word(alphas)
    patt = label("LABEL") + OneOrMore(Word(nums))
    print(patt.parseString("AAB 123 321").dump())

    # Use pop() in a parse action to remove named result (note that corresponding value is not
    # removed from list form of results)
    def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
    patt.addParseAction(remove_LABEL)
    print(patt.parseString("AAB 123 321").dump())

prints::

    ['AAB', '123', '321']
    - LABEL: AAB

    ['AAB', '123', '321']

◆ pprint()

def pprint (   self,
args,
**  kwargs 
)
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .

Example::

    ident = Word(alphas, alphanums)
    num = Word(nums)
    func = Forward()
    term = ident | num | Group('(' + func + ')')
    func <<= ident + Group(Optional(delimitedList(term)))
    result = func.parseString("fna a,b,(fnb c,d,200),100")
    result.pprint(width=40)

prints::

    ['fna',
     ['a',
      'b',
      ['(', 'fnb', ['c', 'd', '200'], ')'],
      '100']]

◆ values()

def values (   self)
Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).

Field Documentation

◆ items

items
static

◆ iteritems

iteritems
static

◆ iterkeys

iterkeys
static

◆ itervalues

itervalues
static

◆ keys

keys
static

◆ values

values
static

The documentation for this class was generated from the following file: