pythonregex

How can I make multiple replacements in a string using a dictionary?


Suppose we have:

d = {
    'Спорт':'Досуг',
    'russianA':'englishA'
}

s = 'Спорт russianA'

How can I replace each appearance within s of any of d's keys, with the corresponding value (in this case, the result would be 'Досуг englishA')?


Solution

  • Using re:

    import re
    
    s = 'Спорт not russianA'
    d = {
    'Спорт':'Досуг',
    'russianA':'englishA'
    }
    keys = (re.escape(k) for k in d.keys())
    pattern = re.compile(r'\b(' + '|'.join(keys) + r')\b')
    result = pattern.sub(lambda x: d[x.group()], s)
    # Output: 'Досуг not englishA'
    

    This will match whole words only. If you don't need that, use the pattern:

    pattern = re.compile('|'.join(re.escape(k) for k in d.keys()))
    

    Note that in this case you should sort the words descending by length if some of your dictionary entries are substrings of others.