[Tutor] Parsing Bible verses
C or L Smith
smiles at worksmail.net
Sat May 23 11:37:34 CEST 2009
Here is something from my toolbox of routines that might be useful for the number ranges:
>>> indices('-5--2')
[-5, -4, -3, -2]
>>> indices('3-4')
[3, 4]
>>> indices('3-4,10')
[3, 4, 10]
/chris
def indices(s,n=None): #("1-3,7")->1,2,3,7;i("1,-3--1")->1,-3,-2,-1; or (slc,n=None)->slc.start,stop,step [for range(n)]
"""Return a list of indices as defined by a MSWord print dialog-like range:
e.g. "1,3,5-7" -> [1, 3, 5, 6, 7]
A trailing comma will be ignored; a trailing dash will generate an error."""
# ranges must be increasing: -3--4 will not generate any numbers
assert type(s) is str
r=[x.strip() for x in s.split(',')]
rv = []
for ri in r:
if not ri: continue
if ri.find('-',1)>0: #ignore - in first position
dashat = ri.find('-',1) #start searching at position 1
nums = ri[:dashat],ri[dashat+1:]
#one might want to use sys.maxint-1 for stop if the '-' is encountered, the
#meaning being "from start to the end (as defined by the code elsewhere")
#but then this should be made into an iterator rather than generating the
#whole list
if nums[1] in ['','-']:
raise ValueError('missing number in request to indices: %s'%ri)
start, stop = [int(x.strip()) for x in nums]
for i in xrange(start, stop+1):
rv.append(i)#yield i
else:
rv.append(int(ri))#yield int(ri)
return rv
More information about the Tutor
mailing list