我想解析生物序列中位置的特定語法。該位置可以有這樣的形式:用pyparsing解析嵌套結構
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 pyparsing返回一個嵌套的字典(和唯一的)?
如何獲得範圍末端和位置偏移的可選性?位置規則中的Or()不會削減它。 (我在範圍的末尾嘗試類似)。理想情況下,我將所有職位視爲最複雜形式(即{start:{base,end},end:{base,end}})的特殊情況,其中較簡單的情況使用0或無)。
謝謝!
而且'或''和''MatchFirst'和'Each'都以列表表達式作爲它們的參數,而不僅僅是表達式。這就是爲什麼我更喜歡操作符覆蓋:'expr1 + expr2 | expr3'比MatchFirst([And([expr1,expr2]),expr3])'更容易遵循。 – PaulMcG