"""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
all_keys = [[ix for ix in i] for i in kwargs.keys()]
for idx, i in enumerate(text):
for key in all_keys:
for char in key:
if char == i:
text[idx] = kwargs.get(''.join(key))
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 4 2012-03-23 20:22:57
+++ revision 5 2012-03-23 20:23:26
@@ -17,7 +17,7 @@
#bring all keys together during character comparisons
all_keys = [[ix for ix in i] for i in kwargs.keys()]
- for idx, i in enumerate(text): #character
+ for idx, i in enumerate(text):
for key in all_keys:
for char in key:
if char == i: