Question

I'm writing a parser for text-based sequence alignment/map (SAM) files. One of the fields is a concatenated list of key-value pairs comprising a single alphabet character and an integer (the integer comes first). I have working code, but it just feels a bit clunky. What's an elegant pattern for parsing a format such as this? Thanks.

Input:

record['cigar_str'] = '6M1I69M1D34M'

Desired output:

record['cigar'] = [
    {'type':'M', 'length':6},
    {'type':'I', 'length':1},
    {'type':'M', 'length':69},
    {'type':'D', 'length':1},
    {'type':'M', 'length':34}
]

EDIT: My current approach

cigarettes = re.findall('[\d]{0,}[A-Z]{1}', record['cigar_str'])
for cigarette in cigarettes:
    if cigarette[-1] == 'I':
        errors['ins'] += int(cigarette[:-1])
    ...
Was it helpful?

Solution

Here's what I'd do:

>>> import re
>>> s = '6M1I69M1D34M'
>>> matches = re.findall(r'(\d+)([A-Z]{1})', s)
>>> import pprint
>>> pprint.pprint([{'type':m[1], 'length':int(m[0])} for m in matches])
[{'length': 6, 'type': 'M'},
 {'length': 1, 'type': 'I'},
 {'length': 69, 'type': 'M'},
 {'length': 1, 'type': 'D'},
 {'length': 34, 'type': 'M'}]

It's pretty similar to what you have, but it uses regex groups to tease out the individual components of the match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top