Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/smanonr..../lib/python3..../site-pac...
File: pyparsing.py
# module pyparsing.py
[0] Fix | Delete
#
[1] Fix | Delete
# Copyright (c) 2003-2016 Paul T. McGuire
[2] Fix | Delete
#
[3] Fix | Delete
# Permission is hereby granted, free of charge, to any person obtaining
[4] Fix | Delete
# a copy of this software and associated documentation files (the
[5] Fix | Delete
# "Software"), to deal in the Software without restriction, including
[6] Fix | Delete
# without limitation the rights to use, copy, modify, merge, publish,
[7] Fix | Delete
# distribute, sublicense, and/or sell copies of the Software, and to
[8] Fix | Delete
# permit persons to whom the Software is furnished to do so, subject to
[9] Fix | Delete
# the following conditions:
[10] Fix | Delete
#
[11] Fix | Delete
# The above copyright notice and this permission notice shall be
[12] Fix | Delete
# included in all copies or substantial portions of the Software.
[13] Fix | Delete
#
[14] Fix | Delete
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
[15] Fix | Delete
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
[16] Fix | Delete
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
[17] Fix | Delete
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
[18] Fix | Delete
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
[19] Fix | Delete
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
[20] Fix | Delete
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[21] Fix | Delete
#
[22] Fix | Delete
[23] Fix | Delete
__doc__ = \
[24] Fix | Delete
"""
[25] Fix | Delete
pyparsing module - Classes and methods to define and execute parsing grammars
[26] Fix | Delete
[27] Fix | Delete
The pyparsing module is an alternative approach to creating and executing simple grammars,
[28] Fix | Delete
vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
[29] Fix | Delete
don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
[30] Fix | Delete
provides a library of classes that you use to construct the grammar directly in Python.
[31] Fix | Delete
[32] Fix | Delete
Here is a program to parse "Hello, World!" (or any greeting of the form
[33] Fix | Delete
C{"<salutation>, <addressee>!"}), built up using L{Word}, L{Literal}, and L{And} elements
[34] Fix | Delete
(L{'+'<ParserElement.__add__>} operator gives L{And} expressions, strings are auto-converted to
[35] Fix | Delete
L{Literal} expressions)::
[36] Fix | Delete
[37] Fix | Delete
from pyparsing import Word, alphas
[38] Fix | Delete
[39] Fix | Delete
# define grammar of a greeting
[40] Fix | Delete
greet = Word(alphas) + "," + Word(alphas) + "!"
[41] Fix | Delete
[42] Fix | Delete
hello = "Hello, World!"
[43] Fix | Delete
print (hello, "->", greet.parseString(hello))
[44] Fix | Delete
[45] Fix | Delete
The program outputs the following::
[46] Fix | Delete
[47] Fix | Delete
Hello, World! -> ['Hello', ',', 'World', '!']
[48] Fix | Delete
[49] Fix | Delete
The Python representation of the grammar is quite readable, owing to the self-explanatory
[50] Fix | Delete
class names, and the use of '+', '|' and '^' operators.
[51] Fix | Delete
[52] Fix | Delete
The L{ParseResults} object returned from L{ParserElement.parseString<ParserElement.parseString>} can be accessed as a nested list, a dictionary, or an
[53] Fix | Delete
object with named attributes.
[54] Fix | Delete
[55] Fix | Delete
The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
[56] Fix | Delete
- extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
[57] Fix | Delete
- quoted strings
[58] Fix | Delete
- embedded comments
[59] Fix | Delete
"""
[60] Fix | Delete
[61] Fix | Delete
__version__ = "2.1.10"
[62] Fix | Delete
__versionTime__ = "07 Oct 2016 01:31 UTC"
[63] Fix | Delete
__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
[64] Fix | Delete
[65] Fix | Delete
import string
[66] Fix | Delete
from weakref import ref as wkref
[67] Fix | Delete
import copy
[68] Fix | Delete
import sys
[69] Fix | Delete
import warnings
[70] Fix | Delete
import re
[71] Fix | Delete
import sre_constants
[72] Fix | Delete
import collections
[73] Fix | Delete
import pprint
[74] Fix | Delete
import traceback
[75] Fix | Delete
import types
[76] Fix | Delete
from datetime import datetime
[77] Fix | Delete
[78] Fix | Delete
try:
[79] Fix | Delete
from _thread import RLock
[80] Fix | Delete
except ImportError:
[81] Fix | Delete
from threading import RLock
[82] Fix | Delete
[83] Fix | Delete
try:
[84] Fix | Delete
from collections import OrderedDict as _OrderedDict
[85] Fix | Delete
except ImportError:
[86] Fix | Delete
try:
[87] Fix | Delete
from ordereddict import OrderedDict as _OrderedDict
[88] Fix | Delete
except ImportError:
[89] Fix | Delete
_OrderedDict = None
[90] Fix | Delete
[91] Fix | Delete
#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
[92] Fix | Delete
[93] Fix | Delete
__all__ = [
[94] Fix | Delete
'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
[95] Fix | Delete
'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
[96] Fix | Delete
'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
[97] Fix | Delete
'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
[98] Fix | Delete
'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
[99] Fix | Delete
'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter',
[100] Fix | Delete
'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
[101] Fix | Delete
'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
[102] Fix | Delete
'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
[103] Fix | Delete
'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
[104] Fix | Delete
'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno',
[105] Fix | Delete
'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
[106] Fix | Delete
'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
[107] Fix | Delete
'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
[108] Fix | Delete
'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
[109] Fix | Delete
'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
[110] Fix | Delete
'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass',
[111] Fix | Delete
'CloseMatch', 'tokenMap', 'pyparsing_common',
[112] Fix | Delete
]
[113] Fix | Delete
[114] Fix | Delete
system_version = tuple(sys.version_info)[:3]
[115] Fix | Delete
PY_3 = system_version[0] == 3
[116] Fix | Delete
if PY_3:
[117] Fix | Delete
_MAX_INT = sys.maxsize
[118] Fix | Delete
basestring = str
[119] Fix | Delete
unichr = chr
[120] Fix | Delete
_ustr = str
[121] Fix | Delete
[122] Fix | Delete
# build list of single arg builtins, that can be used as parse actions
[123] Fix | Delete
singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
[124] Fix | Delete
[125] Fix | Delete
else:
[126] Fix | Delete
_MAX_INT = sys.maxint
[127] Fix | Delete
range = xrange
[128] Fix | Delete
[129] Fix | Delete
def _ustr(obj):
[130] Fix | Delete
"""Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
[131] Fix | Delete
str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
[132] Fix | Delete
then < returns the unicode object | encodes it with the default encoding | ... >.
[133] Fix | Delete
"""
[134] Fix | Delete
if isinstance(obj,unicode):
[135] Fix | Delete
return obj
[136] Fix | Delete
[137] Fix | Delete
try:
[138] Fix | Delete
# If this works, then _ustr(obj) has the same behaviour as str(obj), so
[139] Fix | Delete
# it won't break any existing code.
[140] Fix | Delete
return str(obj)
[141] Fix | Delete
[142] Fix | Delete
except UnicodeEncodeError:
[143] Fix | Delete
# Else encode it
[144] Fix | Delete
ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
[145] Fix | Delete
xmlcharref = Regex('&#\d+;')
[146] Fix | Delete
xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
[147] Fix | Delete
return xmlcharref.transformString(ret)
[148] Fix | Delete
[149] Fix | Delete
# build list of single arg builtins, tolerant of Python version, that can be used as parse actions
[150] Fix | Delete
singleArgBuiltins = []
[151] Fix | Delete
import __builtin__
[152] Fix | Delete
for fname in "sum len sorted reversed list tuple set any all min max".split():
[153] Fix | Delete
try:
[154] Fix | Delete
singleArgBuiltins.append(getattr(__builtin__,fname))
[155] Fix | Delete
except AttributeError:
[156] Fix | Delete
continue
[157] Fix | Delete
[158] Fix | Delete
_generatorType = type((y for y in range(1)))
[159] Fix | Delete
[160] Fix | Delete
def _xml_escape(data):
[161] Fix | Delete
"""Escape &, <, >, ", ', etc. in a string of data."""
[162] Fix | Delete
[163] Fix | Delete
# ampersand must be replaced first
[164] Fix | Delete
from_symbols = '&><"\''
[165] Fix | Delete
to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
[166] Fix | Delete
for from_,to_ in zip(from_symbols, to_symbols):
[167] Fix | Delete
data = data.replace(from_, to_)
[168] Fix | Delete
return data
[169] Fix | Delete
[170] Fix | Delete
class _Constants(object):
[171] Fix | Delete
pass
[172] Fix | Delete
[173] Fix | Delete
alphas = string.ascii_uppercase + string.ascii_lowercase
[174] Fix | Delete
nums = "0123456789"
[175] Fix | Delete
hexnums = nums + "ABCDEFabcdef"
[176] Fix | Delete
alphanums = alphas + nums
[177] Fix | Delete
_bslash = chr(92)
[178] Fix | Delete
printables = "".join(c for c in string.printable if c not in string.whitespace)
[179] Fix | Delete
[180] Fix | Delete
class ParseBaseException(Exception):
[181] Fix | Delete
"""base exception class for all parsing runtime exceptions"""
[182] Fix | Delete
# Performance tuning: we construct a *lot* of these, so keep this
[183] Fix | Delete
# constructor as small and fast as possible
[184] Fix | Delete
def __init__( self, pstr, loc=0, msg=None, elem=None ):
[185] Fix | Delete
self.loc = loc
[186] Fix | Delete
if msg is None:
[187] Fix | Delete
self.msg = pstr
[188] Fix | Delete
self.pstr = ""
[189] Fix | Delete
else:
[190] Fix | Delete
self.msg = msg
[191] Fix | Delete
self.pstr = pstr
[192] Fix | Delete
self.parserElement = elem
[193] Fix | Delete
self.args = (pstr, loc, msg)
[194] Fix | Delete
[195] Fix | Delete
@classmethod
[196] Fix | Delete
def _from_exception(cls, pe):
[197] Fix | Delete
"""
[198] Fix | Delete
internal factory method to simplify creating one type of ParseException
[199] Fix | Delete
from another - avoids having __init__ signature conflicts among subclasses
[200] Fix | Delete
"""
[201] Fix | Delete
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
[202] Fix | Delete
[203] Fix | Delete
def __getattr__( self, aname ):
[204] Fix | Delete
"""supported attributes by name are:
[205] Fix | Delete
- lineno - returns the line number of the exception text
[206] Fix | Delete
- col - returns the column number of the exception text
[207] Fix | Delete
- line - returns the line containing the exception text
[208] Fix | Delete
"""
[209] Fix | Delete
if( aname == "lineno" ):
[210] Fix | Delete
return lineno( self.loc, self.pstr )
[211] Fix | Delete
elif( aname in ("col", "column") ):
[212] Fix | Delete
return col( self.loc, self.pstr )
[213] Fix | Delete
elif( aname == "line" ):
[214] Fix | Delete
return line( self.loc, self.pstr )
[215] Fix | Delete
else:
[216] Fix | Delete
raise AttributeError(aname)
[217] Fix | Delete
[218] Fix | Delete
def __str__( self ):
[219] Fix | Delete
return "%s (at char %d), (line:%d, col:%d)" % \
[220] Fix | Delete
( self.msg, self.loc, self.lineno, self.column )
[221] Fix | Delete
def __repr__( self ):
[222] Fix | Delete
return _ustr(self)
[223] Fix | Delete
def markInputline( self, markerString = ">!<" ):
[224] Fix | Delete
"""Extracts the exception line from the input string, and marks
[225] Fix | Delete
the location of the exception with a special symbol.
[226] Fix | Delete
"""
[227] Fix | Delete
line_str = self.line
[228] Fix | Delete
line_column = self.column - 1
[229] Fix | Delete
if markerString:
[230] Fix | Delete
line_str = "".join((line_str[:line_column],
[231] Fix | Delete
markerString, line_str[line_column:]))
[232] Fix | Delete
return line_str.strip()
[233] Fix | Delete
def __dir__(self):
[234] Fix | Delete
return "lineno col line".split() + dir(type(self))
[235] Fix | Delete
[236] Fix | Delete
class ParseException(ParseBaseException):
[237] Fix | Delete
"""
[238] Fix | Delete
Exception thrown when parse expressions don't match class;
[239] Fix | Delete
supported attributes by name are:
[240] Fix | Delete
- lineno - returns the line number of the exception text
[241] Fix | Delete
- col - returns the column number of the exception text
[242] Fix | Delete
- line - returns the line containing the exception text
[243] Fix | Delete
[244] Fix | Delete
Example::
[245] Fix | Delete
try:
[246] Fix | Delete
Word(nums).setName("integer").parseString("ABC")
[247] Fix | Delete
except ParseException as pe:
[248] Fix | Delete
print(pe)
[249] Fix | Delete
print("column: {}".format(pe.col))
[250] Fix | Delete
[251] Fix | Delete
prints::
[252] Fix | Delete
Expected integer (at char 0), (line:1, col:1)
[253] Fix | Delete
column: 1
[254] Fix | Delete
"""
[255] Fix | Delete
pass
[256] Fix | Delete
[257] Fix | Delete
class ParseFatalException(ParseBaseException):
[258] Fix | Delete
"""user-throwable exception thrown when inconsistent parse content
[259] Fix | Delete
is found; stops all parsing immediately"""
[260] Fix | Delete
pass
[261] Fix | Delete
[262] Fix | Delete
class ParseSyntaxException(ParseFatalException):
[263] Fix | Delete
"""just like L{ParseFatalException}, but thrown internally when an
[264] Fix | Delete
L{ErrorStop<And._ErrorStop>} ('-' operator) indicates that parsing is to stop
[265] Fix | Delete
immediately because an unbacktrackable syntax error has been found"""
[266] Fix | Delete
pass
[267] Fix | Delete
[268] Fix | Delete
#~ class ReparseException(ParseBaseException):
[269] Fix | Delete
#~ """Experimental class - parse actions can raise this exception to cause
[270] Fix | Delete
#~ pyparsing to reparse the input string:
[271] Fix | Delete
#~ - with a modified input string, and/or
[272] Fix | Delete
#~ - with a modified start location
[273] Fix | Delete
#~ Set the values of the ReparseException in the constructor, and raise the
[274] Fix | Delete
#~ exception in a parse action to cause pyparsing to use the new string/location.
[275] Fix | Delete
#~ Setting the values as None causes no change to be made.
[276] Fix | Delete
#~ """
[277] Fix | Delete
#~ def __init_( self, newstring, restartLoc ):
[278] Fix | Delete
#~ self.newParseText = newstring
[279] Fix | Delete
#~ self.reparseLoc = restartLoc
[280] Fix | Delete
[281] Fix | Delete
class RecursiveGrammarException(Exception):
[282] Fix | Delete
"""exception thrown by L{ParserElement.validate} if the grammar could be improperly recursive"""
[283] Fix | Delete
def __init__( self, parseElementList ):
[284] Fix | Delete
self.parseElementTrace = parseElementList
[285] Fix | Delete
[286] Fix | Delete
def __str__( self ):
[287] Fix | Delete
return "RecursiveGrammarException: %s" % self.parseElementTrace
[288] Fix | Delete
[289] Fix | Delete
class _ParseResultsWithOffset(object):
[290] Fix | Delete
def __init__(self,p1,p2):
[291] Fix | Delete
self.tup = (p1,p2)
[292] Fix | Delete
def __getitem__(self,i):
[293] Fix | Delete
return self.tup[i]
[294] Fix | Delete
def __repr__(self):
[295] Fix | Delete
return repr(self.tup[0])
[296] Fix | Delete
def setOffset(self,i):
[297] Fix | Delete
self.tup = (self.tup[0],i)
[298] Fix | Delete
[299] Fix | Delete
class ParseResults(object):
[300] Fix | Delete
"""
[301] Fix | Delete
Structured parse results, to provide multiple means of access to the parsed data:
[302] Fix | Delete
- as a list (C{len(results)})
[303] Fix | Delete
- by list index (C{results[0], results[1]}, etc.)
[304] Fix | Delete
- by attribute (C{results.<resultsName>} - see L{ParserElement.setResultsName})
[305] Fix | Delete
[306] Fix | Delete
Example::
[307] Fix | Delete
integer = Word(nums)
[308] Fix | Delete
date_str = (integer.setResultsName("year") + '/'
[309] Fix | Delete
+ integer.setResultsName("month") + '/'
[310] Fix | Delete
+ integer.setResultsName("day"))
[311] Fix | Delete
# equivalent form:
[312] Fix | Delete
# date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
[313] Fix | Delete
[314] Fix | Delete
# parseString returns a ParseResults object
[315] Fix | Delete
result = date_str.parseString("1999/12/31")
[316] Fix | Delete
[317] Fix | Delete
def test(s, fn=repr):
[318] Fix | Delete
print("%s -> %s" % (s, fn(eval(s))))
[319] Fix | Delete
test("list(result)")
[320] Fix | Delete
test("result[0]")
[321] Fix | Delete
test("result['month']")
[322] Fix | Delete
test("result.day")
[323] Fix | Delete
test("'month' in result")
[324] Fix | Delete
test("'minutes' in result")
[325] Fix | Delete
test("result.dump()", str)
[326] Fix | Delete
prints::
[327] Fix | Delete
list(result) -> ['1999', '/', '12', '/', '31']
[328] Fix | Delete
result[0] -> '1999'
[329] Fix | Delete
result['month'] -> '12'
[330] Fix | Delete
result.day -> '31'
[331] Fix | Delete
'month' in result -> True
[332] Fix | Delete
'minutes' in result -> False
[333] Fix | Delete
result.dump() -> ['1999', '/', '12', '/', '31']
[334] Fix | Delete
- day: 31
[335] Fix | Delete
- month: 12
[336] Fix | Delete
- year: 1999
[337] Fix | Delete
"""
[338] Fix | Delete
def __new__(cls, toklist=None, name=None, asList=True, modal=True ):
[339] Fix | Delete
if isinstance(toklist, cls):
[340] Fix | Delete
return toklist
[341] Fix | Delete
retobj = object.__new__(cls)
[342] Fix | Delete
retobj.__doinit = True
[343] Fix | Delete
return retobj
[344] Fix | Delete
[345] Fix | Delete
# Performance tuning: we construct a *lot* of these, so keep this
[346] Fix | Delete
# constructor as small and fast as possible
[347] Fix | Delete
def __init__( self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance ):
[348] Fix | Delete
if self.__doinit:
[349] Fix | Delete
self.__doinit = False
[350] Fix | Delete
self.__name = None
[351] Fix | Delete
self.__parent = None
[352] Fix | Delete
self.__accumNames = {}
[353] Fix | Delete
self.__asList = asList
[354] Fix | Delete
self.__modal = modal
[355] Fix | Delete
if toklist is None:
[356] Fix | Delete
toklist = []
[357] Fix | Delete
if isinstance(toklist, list):
[358] Fix | Delete
self.__toklist = toklist[:]
[359] Fix | Delete
elif isinstance(toklist, _generatorType):
[360] Fix | Delete
self.__toklist = list(toklist)
[361] Fix | Delete
else:
[362] Fix | Delete
self.__toklist = [toklist]
[363] Fix | Delete
self.__tokdict = dict()
[364] Fix | Delete
[365] Fix | Delete
if name is not None and name:
[366] Fix | Delete
if not modal:
[367] Fix | Delete
self.__accumNames[name] = 0
[368] Fix | Delete
if isinstance(name,int):
[369] Fix | Delete
name = _ustr(name) # will always return a str, but use _ustr for consistency
[370] Fix | Delete
self.__name = name
[371] Fix | Delete
if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None,'',[])):
[372] Fix | Delete
if isinstance(toklist,basestring):
[373] Fix | Delete
toklist = [ toklist ]
[374] Fix | Delete
if asList:
[375] Fix | Delete
if isinstance(toklist,ParseResults):
[376] Fix | Delete
self[name] = _ParseResultsWithOffset(toklist.copy(),0)
[377] Fix | Delete
else:
[378] Fix | Delete
self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
[379] Fix | Delete
self[name].__name = name
[380] Fix | Delete
else:
[381] Fix | Delete
try:
[382] Fix | Delete
self[name] = toklist[0]
[383] Fix | Delete
except (KeyError,TypeError,IndexError):
[384] Fix | Delete
self[name] = toklist
[385] Fix | Delete
[386] Fix | Delete
def __getitem__( self, i ):
[387] Fix | Delete
if isinstance( i, (int,slice) ):
[388] Fix | Delete
return self.__toklist[i]
[389] Fix | Delete
else:
[390] Fix | Delete
if i not in self.__accumNames:
[391] Fix | Delete
return self.__tokdict[i][-1][0]
[392] Fix | Delete
else:
[393] Fix | Delete
return ParseResults([ v[0] for v in self.__tokdict[i] ])
[394] Fix | Delete
[395] Fix | Delete
def __setitem__( self, k, v, isinstance=isinstance ):
[396] Fix | Delete
if isinstance(v,_ParseResultsWithOffset):
[397] Fix | Delete
self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
[398] Fix | Delete
sub = v[0]
[399] Fix | Delete
elif isinstance(k,(int,slice)):
[400] Fix | Delete
self.__toklist[k] = v
[401] Fix | Delete
sub = v
[402] Fix | Delete
else:
[403] Fix | Delete
self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
[404] Fix | Delete
sub = v
[405] Fix | Delete
if isinstance(sub,ParseResults):
[406] Fix | Delete
sub.__parent = wkref(self)
[407] Fix | Delete
[408] Fix | Delete
def __delitem__( self, i ):
[409] Fix | Delete
if isinstance(i,(int,slice)):
[410] Fix | Delete
mylen = len( self.__toklist )
[411] Fix | Delete
del self.__toklist[i]
[412] Fix | Delete
[413] Fix | Delete
# convert int to slice
[414] Fix | Delete
if isinstance(i, int):
[415] Fix | Delete
if i < 0:
[416] Fix | Delete
i += mylen
[417] Fix | Delete
i = slice(i, i+1)
[418] Fix | Delete
# get removed indices
[419] Fix | Delete
removed = list(range(*i.indices(mylen)))
[420] Fix | Delete
removed.reverse()
[421] Fix | Delete
# fixup indices in token dictionary
[422] Fix | Delete
for name,occurrences in self.__tokdict.items():
[423] Fix | Delete
for j in removed:
[424] Fix | Delete
for k, (value, position) in enumerate(occurrences):
[425] Fix | Delete
occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
[426] Fix | Delete
else:
[427] Fix | Delete
del self.__tokdict[i]
[428] Fix | Delete
[429] Fix | Delete
def __contains__( self, k ):
[430] Fix | Delete
return k in self.__tokdict
[431] Fix | Delete
[432] Fix | Delete
def __len__( self ): return len( self.__toklist )
[433] Fix | Delete
def __bool__(self): return ( not not self.__toklist )
[434] Fix | Delete
__nonzero__ = __bool__
[435] Fix | Delete
def __iter__( self ): return iter( self.__toklist )
[436] Fix | Delete
def __reversed__( self ): return iter( self.__toklist[::-1] )
[437] Fix | Delete
def _iterkeys( self ):
[438] Fix | Delete
if hasattr(self.__tokdict, "iterkeys"):
[439] Fix | Delete
return self.__tokdict.iterkeys()
[440] Fix | Delete
else:
[441] Fix | Delete
return iter(self.__tokdict)
[442] Fix | Delete
[443] Fix | Delete
def _itervalues( self ):
[444] Fix | Delete
return (self[k] for k in self._iterkeys())
[445] Fix | Delete
[446] Fix | Delete
def _iteritems( self ):
[447] Fix | Delete
return ((k, self[k]) for k in self._iterkeys())
[448] Fix | Delete
[449] Fix | Delete
if PY_3:
[450] Fix | Delete
keys = _iterkeys
[451] Fix | Delete
"""Returns an iterator of all named result keys (Python 3.x only)."""
[452] Fix | Delete
[453] Fix | Delete
values = _itervalues
[454] Fix | Delete
"""Returns an iterator of all named result values (Python 3.x only)."""
[455] Fix | Delete
[456] Fix | Delete
items = _iteritems
[457] Fix | Delete
"""Returns an iterator of all named result key-value tuples (Python 3.x only)."""
[458] Fix | Delete
[459] Fix | Delete
else:
[460] Fix | Delete
iterkeys = _iterkeys
[461] Fix | Delete
"""Returns an iterator of all named result keys (Python 2.x only)."""
[462] Fix | Delete
[463] Fix | Delete
itervalues = _itervalues
[464] Fix | Delete
"""Returns an iterator of all named result values (Python 2.x only)."""
[465] Fix | Delete
[466] Fix | Delete
iteritems = _iteritems
[467] Fix | Delete
"""Returns an iterator of all named result key-value tuples (Python 2.x only)."""
[468] Fix | Delete
[469] Fix | Delete
def keys( self ):
[470] Fix | Delete
"""Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x)."""
[471] Fix | Delete
return list(self.iterkeys())
[472] Fix | Delete
[473] Fix | Delete
def values( self ):
[474] Fix | Delete
"""Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x)."""
[475] Fix | Delete
return list(self.itervalues())
[476] Fix | Delete
[477] Fix | Delete
def items( self ):
[478] Fix | Delete
"""Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x)."""
[479] Fix | Delete
return list(self.iteritems())
[480] Fix | Delete
[481] Fix | Delete
def haskeys( self ):
[482] Fix | Delete
"""Since keys() returns an iterator, this method is helpful in bypassing
[483] Fix | Delete
code that looks for the existence of any defined results names."""
[484] Fix | Delete
return bool(self.__tokdict)
[485] Fix | Delete
[486] Fix | Delete
def pop( self, *args, **kwargs):
[487] Fix | Delete
"""
[488] Fix | Delete
Removes and returns item at specified index (default=C{last}).
[489] Fix | Delete
Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
[490] Fix | Delete
argument or an integer argument, it will use C{list} semantics
[491] Fix | Delete
and pop tokens from the list of parsed tokens. If passed a
[492] Fix | Delete
non-integer argument (most likely a string), it will use C{dict}
[493] Fix | Delete
semantics and pop the corresponding value from any defined
[494] Fix | Delete
results names. A second default return value argument is
[495] Fix | Delete
supported, just as in C{dict.pop()}.
[496] Fix | Delete
[497] Fix | Delete
Example::
[498] Fix | Delete
def remove_first(tokens):
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function