Replace all the occurrences of specific words

前端 未结 4 1843
暗喜
暗喜 2020-12-11 02:00

Suppose that I have the following sentence:

bean likes to sell his beans

and I want to replace all occurrences of specific words with other

4条回答
  •  臣服心动
    2020-12-11 02:13

    If you replace each word one at a time, you might replace words several times (and not get what you want). To avoid this, you can use a function or lambda:

    d = {'bean':'robert', 'beans':'cars'}
    str_in = 'bean likes to sell his beans'
    str_out = re.sub(r'\b(\w+)\b', lambda m:d.get(m.group(1), m.group(1)), str_in)
    

    That way, once bean is replaced by robert, it won't be modified again (even if robert is also in your input list of words).

    As suggested by georg, I edited this answer with dict.get(key, default_value). Alternative solution (also suggested by georg):

    str_out = re.sub(r'\b(%s)\b' % '|'.join(d.keys()), lambda m:d.get(m.group(1), m.group(1)), str_in)
    

提交回复
热议问题