need simple parsing ability

Scott David Daniels Scott.Daniels at Acm.Org
Fri Jul 16 23:26:30 CEST 2004


george young wrote:

...
> Mmm, not quite.  If ns=='foo08-11', your fs==[foo8, foo9, foo10, foo11] 
> which is wrong.  It should yield  fs==[foo08, foo09, foo10, foo11].
> I.e., it must maintain leading zeros in ranges.
>>>>
>>>>Can anyone suggest a clean way of doing this?  I don't mind
>>>>installing and importing some parsing package, as long as my code
>>>>using it is clear and simple.  Performance is not an issue.
>>>>
>>>>
>>>>-- George Young

Here's a $50 solution.  Using the code below, you can do:

     mywafers = allwafers('q9-43, s12, a11-23')

Then you can use tests like:

    if 'wafer23' in mywafers:
        ...

---

import sets

def elements(wafers):
     '''get wafer names from wafer-names and wafer-name-ranges'''
     for element in wafers:
         if '-' not in element:
             yield element    # simple name
             continue
         # name with range
         start, final = element.split('-')
         preamble = start.rstrip('0123456789')  # header
         initial = start[len(preamble):]
         if len(final) == len(initial) or initial.startswith('0'):
             # use fixed length strings.
             assert len(initial) >= len(final)  # eg: foo01-009
             pattern = preamble + '%0' + str(len(initial)) + 'd'
         else:
             # unequal length: should be foo08-09, not foo008-9
             assert not (final.startswith('0') or initial.startswith('0'))
             pattern = preamble + '%d'
         for number in range(int(initial), int(final)+1):
             yield pattern % number

def allwafers(spec):
     return sets.Set(elements([element.strip()
                               for element in spec.split(',')]))

if __name__ == '__main__':
     ns = ('9,foo7-9,2-4,xxx,5, 6, 7, 8, 9, bar, foo_6, foo_10,'
                ' foo_11, q08-12')
     nr = ('9 foo7 foo8 foo9 2 3 4 xxx 5 6 7 8 9 bar foo_6 foo_10 '
           ' foo_11 q08 q09 q10 q11 q12').split()
     assert sets.Set(nr) == allwafers(ns)


-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list