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?
CodePudding user response:
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 andcounter.i = 0
sets thei
property to0
re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)
finds all occurrences ofkey
that is searched as a whole word (accounting for any special chars in thekey
) and replaces it with therepl
function- In the
repl
function, thecounter.i
is incremented and if the found match is inNumberL
, the replacement takes place, else, the found match is put back.