感谢大家的帮助,我走到了这一步,但我有一些新的问题,我希望有人能帮助我,我找到了下面的单词,我想用另一个词取代他们,但这段代码只适用于第一个单词
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])结果:你突然说再见了,虽然我热情洋溢地爱上了克莱斯,但我的“希望救世主”却孤独地生活了一百年。
我编辑并高亮显示了错误的单词。
有人能帮我解决这个问题吗?
发布于 2022-06-17 09:42:21
您可以使用
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]))输出:
Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope Cleis stay lonely and live for a hundred years见Python演示。
详细信息
counter = lambda x: None设置一个计数器对象,counter.i = 0将i属性设置为0re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)查找作为一个单词搜索的所有key (说明key中的任何特殊字符),并将其替换为repl函数。repl函数中,counter.i是递增的,如果发现的匹配在NumberL中,则替换发生,否则,返回找到的匹配。https://stackoverflow.com/questions/72657189
复制相似问题