2011-07-14 10 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を使用してみましたが、それは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の「the」があるかもしれません。それはあなたの方法を使用してまだ行うことができますが、私はより簡潔なアプローチを探しています。しかし、あなたの助けに+1。 – Legend

+0

ありがとうございます - 最後の1つの解決策を確認してください。 –

+0

単に素晴らしいです!あなたの時間をもう一度ありがとう。 – Legend

2

あなたはでどのように見、置き換えるパラメータとしてコールバック関数を使用することができます。

http://docs.python.org/library/re.html#re.sub

はその後、いくつかのカウンタを使用するとカウンタ値に応じて交換してください。

+0

ありがとうございます。私はそれを今遊んで戻ってくるだろう。 – Legend

4

先生の最後の答えは、replacementという変数を破壊しています。ここに空けずにやる方法があります。replacement

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

+1です。ありがとうございました。 – Legend

関連する問題