inserting bracketings into a string

Peter Otten __peter__ at web.de
Wed Nov 17 09:17:44 CET 2004


Steven Bethard wrote:

> I'm trying to insert some bracketings in a string based on a set of
> labels and associated start and end indices.  For example, I'd like to
> do something like:
> 
>>>> text = 'abcde fgh ijklmnop qrstu vw xyz'
>>>> spans = [('A', 0, 9), ('B', 6, 9), ('C', 25, 31)]
>>>> insert_bracketings(text, spans)
> '[A abcde [B fgh]] ijklmnop qrstu [C vw xyz]'

Not tested beyond what you see:

text = 'abcde fgh ijklmnop qrstu vw xyz'
spans = [('A', 0, 9), ('B', 6, 9), ('C', 25, 31)]

def insert_bracketings(text, spans):
    inserts = [(s, "[%s " % r) for (r, s, t) in spans]
    inserts.extend([(t, "]") for (r, s, t) in spans])
    inserts.sort()
    inserts.reverse()
    text = list(text)
    for (r, s) in inserts:
        text.insert(r, s)
    return "".join(text)
        
assert ('[A abcde [B fgh]] ijklmnop qrstu [C vw xyz]' 
          == insert_bracketings(text, spans))
    
Peter
 




More information about the Python-list mailing list