2011-07-14 12 views
7

我有一個正則表達式這樣的更換每場比賽:用不同的詞

findthe = re.compile(r" the ") 
replacement = ["firstthe", "secondthe"] 
sentence = "This is the first sentence in the whole universe!" 

我所試圖做的是從列表與相關的替換詞替換每次出現這樣最終判決會是這樣的:

>>> print sentence 
This is firstthe first sentence in secondthe whole universe 

我試圖用re.sub內部for循環中列舉了更換,但它看起來像re.sub回報所有事件。有人能告訴我如何有效地做到這一點?

回答

6

如果不需要使用正則表達式比,你可以嘗試使用下面的代碼:

replacement = ["firstthe", "secondthe"] 
sentence = "This is the first sentence in the whole universe!" 

words = sentence.split() 

counter = 0 
for i,word in enumerate(words): 
    if word == 'the': 
     words[i] = replacement[counter] 
     counter += 1 

sentence = ' '.join(words) 

或者類似的東西,這將工作太:

import re 
findthe = re.compile(r"\b(the)\b") 
print re.sub(findthe, replacement[1],re.sub(findthe, replacement[0],sentence, 1), 1) 

而且至少:

re.sub(findthe, lambda matchObj: replacement.pop(0),sentence) 
+0

不幸的是,替換邏輯對我而言稍微複雜一些。我提供的是一個測試用例。就我而言,可能會有10到20個。它仍然可以使用你的方法完成,但我正在尋找更簡潔的方法。但+1爲你的幫助。 – Legend

+0

謝謝 - 檢查最後一個解決方案。 –

+0

簡直太棒了!再次感謝您的時間。 – Legend

4

Artsiom的最後一個答案是破壞性的replacement變量。這裏有一種不排空的方法replacement

re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence) 
+0

+1。謝謝。 – Legend