Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading