感謝大家的幫助,我完成了這一步,但我有一些新問題希望有人能幫助我,我找到了以下你的話,并想用另一個詞替換它們,但此代碼僅適用于第一個詞
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])
結果:突然你說再見了,雖然我愛上了克萊斯,但我還是“跳克萊索”孤獨地活了一百年。
我編輯并突出顯示了錯誤詞。
有人可以給我一個解決這個問題的方法嗎?
uj5u.com熱心網友回復:
您可以使用
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://www.uj5u.com/yidong/492367.html
