Welcome, guest | Sign In | My Account | Store | Cart
"""simplified extension of the replace function in python"""

def replacen(text, kwargs):
    """any single character of `text` in `kwargs[v]` is replaced by `v`
    >>> consonants = replacen('abcdefghijklmnopqrstuvwxyz', {'aeiou':''})
    """
    
    try:
        text = [i for i in text]
    except (ValueError, TypeError):
        raise TypeError("`text` parameter must have valid str type")
        
    #check the contents of each key, make sure there's no overlap:
    collisions = any_key_collisions(kwargs)
    if collisions:
        raise KeyError("keys have duplicate find-replace strings: '%s'" % collisions)
    
    #bring all keys together during character comparisons
    model_keys = [[ix for ix in i] for i in kwargs.keys()]
    for idx, i in enumerate(text):
        for ix in model_keys:
            for key in ix:
                if key == i:
                    text[idx] = kwargs.get(''.join(ix))
    return ''.join(text)

def any_key_collisions(dictionary):
    """ensures no keys contain any other key element, across all keys"""
    members = [i for i in dictionary.keys()]
    dups = ''
    for idx, _ in enumerate(members):
        candidate = members[idx * -1]
        if candidate in members[: idx * -1]:
            dups += candidate
    return ''.join(set(dups))
    
if __name__ == '__main__':
    original = "\"This is a quote, 'from a famous book'.\""
    no_punc = replacen(original, {'"\'.' : '', ',': ' --'})
    print original, '\n', no_punc

Diff to Previous Revision

--- revision 2 2012-03-23 20:18:54
+++ revision 3 2012-03-23 20:21:11
@@ -15,7 +15,7 @@
     if collisions:
         raise KeyError("keys have duplicate find-replace strings: '%s'" % collisions)
     
-    #model the keys
+    #bring all keys together during character comparisons
     model_keys = [[ix for ix in i] for i in kwargs.keys()]
     for idx, i in enumerate(text):
         for ix in model_keys:

History