python-regex change any word I want

thanks to everyone’s help i got to this step but I have a few new problems that I hope someone can help me with,I found the following you words and want to replace them with another word but this code only works for the first word

import Re
text = 'Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years'
def replace(text,key,value,NumberL):
    matches = list(re.finditer(key,text,re.I))
    for i in NumberL:
        newT = matches[i-1]
        text = text[:newT.start(0)] + value + text[newT.end(0):]
    print(text)
replace(text,'you','Cleis',[2,3])

result: Suddenly you said goodbye, even though I was passionately in love with Cleis, I ”hopCleisou” stay lonely and live for a hundred years.

I edited and highlighted the error word.

Can someone give me a solution to this problem?

>Solution :

You can use

import re

def repl(m, value, counter, NumberL):
    counter.i += 1
    if counter.i in NumberL:
        return value
    return m.group()

def replace(text,key,value,NumberL):
    counter = lambda x: None
    counter.i = 0
    return re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)
    
text = 'Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years'
print(replace(text,'you','Cleis',[2,3]))

Output:

Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope Cleis stay lonely and live for a hundred years

See the Python demo.

Details:

  • counter = lambda x: None sets up a counter object and counter.i = 0 sets the i property to 0
  • re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text) finds all occurrences of key that is searched as a whole word (accounting for any special chars in the key) and replaces it with the repl function
  • In the repl function, the counter.i is incremented and if the found match is in NumberL, the replacement takes place, else, the found match is put back.

Leave a Reply