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)
    
    #model the keys
    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 1 2012-03-23 20:16:13
+++ revision 2 2012-03-23 20:18:54
@@ -26,7 +26,7 @@
 
 def any_key_collisions(dictionary):
     """ensures no keys contain any other key element, across all keys"""
-    members = [i for i in ''.join([i for i in dictionary.keys()])]
+    members = [i for i in dictionary.keys()]
     dups = ''
     for idx, _ in enumerate(members):
         candidate = members[idx * -1]
@@ -36,5 +36,5 @@
     
 if __name__ == '__main__':
     original = "\"This is a quote, 'from a famous book'.\""
-    no_punc = replacen(text, {'"\'.' : '', ',': ' --'})
+    no_punc = replacen(original, {'"\'.' : '', ',': ' --'})
     print original, '\n', no_punc

History