带模式匹配的点符号解析器
dotted-notation的Python项目详细描述
虚线
有时,您希望从深度嵌套的数据结构中获取数据。星罗棋布的 记谱法对你有帮助。在
假设你有一个字典包含一个包含列表和 您希望从嵌套列表中获取第i个值。在
>>> import dotted
>>> d = {'hi': {'there': [1, 2, 3]}}
>>> dotted.get(d, 'hi.there[1]')
2
语法
点符号看起来类似于python。dot字段和slot字段,
e、 g.方括号,内部调用__getitem__
。一个dot字段期望看到
像字典一样的物体。一个slot字段偏向于序列(比如
列表、元组和str),但也可以作用于dict。虚线也支持
切片表示法以及下面讨论的转换。在
图案
你可以用虚线来匹配图案。您可以匹配通配符或常规 表达。在
^{pr2}$虚线将返回与模式匹配的所有值。在
切片
也支持切片。点式切片的工作原理与python切片类似 这就意味着。在
>>> import dotted
>>> d = {'hi': {'there': [1, 2, 3]}, 'bye': {'there': [4, 5, 6]}}
>>> dotted.get(d, 'hi.there[::2]')
[1, 3]
>>> dotted.get(d, '*.there[1:]')
([2, 3], [5, 6])
“+”运算符
slot和slices都支持“+”运算符,它引用 顺序。您可以在序列的末尾附加一个项或切片。在
>>> import dotted
>>> d = {'hi': {'there': [1, 2, 3]}, 'bye': {'there': [4, 5, 6]}}
>>> dotted.update(d, '*.there[+]', 8)
{'hi': {'there': [1, 2, 3, 8]}, 'bye': {'there': [4, 5, 6, 8]}}
>>> dotted.update(d, '*.there[+:]', [999])
{'hi': {'there': [1, 2, 3, 8, 999]}, 'bye': {'there': [4, 5, 6, 8, 999]}}
变换
您可以选择将转换添加到点符号的末尾。这些遗嘱
应用于get
和{|
运算符分隔
多个可能会被连锁在一起。可以使用参数化转换
:
运算符。在
>>> import dotted
>>> d = [1, '2', 3]
>>> dotted.get(d, '[1]')
'2'
>>> dotted.get(d, '[1]|int')
2
>>> dotted.get(d, '[0]|str:number=%d')
'number=1'
您可以通过register
或@transform
注册新的转换
装饰工。看看变换.py对于预注册。在
- 项目
标签: