regex - How to use str.replace() with a dictionary of replacements? Python -
given dictionary of replacements, key = replaced
, value = replacements
, e.g.:
replacements = {u'\u2014':'-', u'\u2019':"'", u'\u2018':"'", u'\u201d':'"', u'\u201c':'"'}
how perform replace without iterating through replacements.keys()
?
how same operation possible regex, re.sub()
?
i have been doing way:
for r in replacements: sentence = sentence.replace(r,replacements[r])
you looking unicode.translate()
instead. takes mapping of unicode ordinals (integer numbers) , values should ordinals too, or unicode strings, or none
signal delete character:
replacements = {ord(k): ord(v) k, v in replacements.iteritems()} sentence = sentence.translate(replacements)
demo:
>>> replacements = {ord(k): ord(v) k, v in replacements.iteritems()} >>> replacements {8216: 39, 8217: 39, 8212: 45, 8221: 34, 8220: 34} >>> u'\u2019hello world! \u2014 rock!\u2018'.translate(replacements) u"'hello world! - rock!'"
Comments
Post a Comment