【发布时间】:2013-10-19 01:40:46
【问题描述】:
我正在尝试解析生物序列中位置的特定语法。职位可以有如下形式:
12 -- a simple position in the sequence
12+34 -- a complex position as a base (12) and offset(+34)
12_56 -- a range, from 12 to 56
12+34_56-78 -- a range as a start to end, where either or both may be simple or complex
我希望将这些解析为字典,大致如下:
12 -> { 'start': { 'base': 12, 'offset': 0 }, 'end': None }
12+34 -> { 'start': { 'base': 12, 'offset': 34 }, 'end': None }
12_56 -> { 'start': { 'base': 12, 'offset': 0 },
'end': { 'base': 56, 'offset': 0 } }
12+34_56-78 -> { 'start': { 'base': 12, 'offset': 0 },
'end': { 'base': 56, 'offset': -78 } }
我已经使用 pyparsing 进行了几次测试。这是一个:
from pyparsing import *
integer = Word(nums)
signed_integer = Word('+-', nums)
underscore = Suppress('_')
position = integer.setResultsName('base') + Or(signed_integer,Empty).setResultsName('offset')
interval = position.setResultsName('start') + Or(underscore + position,Empty).setResultsName('end')
结果接近我想要的:
In [20]: hgvspyparsing.interval.parseString('12-34_56+78').asDict()
Out[20]:
{'base': '56',
'end': (['56', '+78'], {'base': [('56', 0)], 'offset': [((['+78'], {}), 1)]}),
'offset': (['+78'], {}),
'start': (['12', '-34'], {'base': [('12', 0)], 'offset': [((['-34'], {}), 1)]})}
两个问题:
asDict() 仅适用于根 parseResult。有没有办法哄骗 pyparsing 返回一个嵌套的 dict(而且只有那个)?
如何获得范围结尾的可选性和位置的偏移量?位置规则中的 Or() 并没有削减它。 (我对范围的结尾进行了类似的尝试。)理想情况下,我会将所有位置视为最复杂形式的特殊情况(即 { start: {base, end}, end: { base, end } }),其中更简单的情况使用 0 或 None。)
谢谢!
【问题讨论】:
-
还有
Or、And、MatchFirst和Each都将表达式列表作为参数,而不仅仅是表达式。这就是为什么我更喜欢运算符覆盖的原因:expr1 + expr2 | expr3比MatchFirst([And([expr1,expr2]), expr3])更容易理解。