type Dict
source code
object --+
|
ParserElement --+
|
ParseElementEnhance --+
|
TokenConverter --+
|
Dict
Converter to return a repetitive expression as a list, but also as a
dictionary. Each element can also be referenced using the first token in
the expression as its key. Useful for tabular report scraping when the
first column can be used as a item key.
Example:
data_word = Word(alphas)
label = data_word + FollowedBy(':')
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
# print attributes as plain groups
print(OneOrMore(attr_expr).parseString(text).dump())
# instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
result = Dict(OneOrMore(Group(attr_expr))).parseString(text)
print(result.dump())
# access named fields as dict entries, or output as dict
print(result['shape'])
print(result.asDict())
prints:
['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
{'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
See more examples at ParseResults of accessing fields by results name.
|
|
|
|
Inherited from ParseElementEnhance :
__str__ ,
checkRecursion ,
ignore ,
leaveWhitespace ,
parseImpl ,
streamline ,
validate
Inherited from ParserElement :
__add__ ,
__and__ ,
__call__ ,
__eq__ ,
__hash__ ,
__invert__ ,
__mul__ ,
__ne__ ,
__or__ ,
__radd__ ,
__rand__ ,
__repr__ ,
__req__ ,
__rmul__ ,
__rne__ ,
__ror__ ,
__rsub__ ,
__rxor__ ,
__sub__ ,
__xor__ ,
addCondition ,
addParseAction ,
canParseNext ,
copy ,
matches ,
parseFile ,
parseString ,
parseWithTabs ,
preParse ,
runTests ,
scanString ,
searchString ,
setBreak ,
setDebug ,
setDebugActions ,
setFailAction ,
setName ,
setParseAction ,
setResultsName ,
setWhitespaceChars ,
split ,
suppress ,
transformString ,
tryParse
|