2016-08-18 12 views
0

文字列 "+"を "!"で置き換える文字列 "*"を特定のテキストの "!!"で置き換えるプログラムを書いています。例として、私はから行く必要があります。テキスト内の文字列を置換することを繰り返す

some_text = ‘here is +some*+ text and also +some more*+ text here’ 

some_text_new = ‘here is !some!! text and also !some more!! text here’ 

にあなたは「+」と「* +」私のテキストに特定の単語を囲むことに気づくでしょう。私がプログラムを実行した後、それらの単語は代わりに "!"と "!!"の間に囲む必要があります。

私は以下のコードを書いていますが、正しい出力を出す前に数回繰り返します。どのように反復を避けることができますか?...。

def many_cues(value): 
     if has_cue_marks(value) is True: 
      add_text(value) 
      #print value 


    def has_cue_marks(value): 
     return '+' in value and'+*' in value 

    def add_text(value): 
     n = '+' 
     m = "+*" 
     text0 = value 
     for n in text0: 
      text1 = text0.replace(n, ‘!', 3) 
      print text1 
     for m in text0: 
      text2 = text0.replace(m, ‘!!’, 3) 
      print text2 
+0

を交換したい二つのパターンに共通の文字を持っているので、それはおそらくにより理にかなって正規表現のグループグループの順序が重要であること

import re def replacer(matchObj): if matchObj.group(1) == '*+': return '!!' elif matchObj.group(2) == '+' return '!' text = 'here is +some*+ text and also +some more*+ text here' replaced = re.sub(r'(\*\+)|(\+)', replacer, text) 

は予告を使用して行うことができます最初に '' + ''を検索するとすべての' '+" 'が' '!''に変更され、 '' * * ''のインスタンスは'!*" 'の代わりに無視されます。また、あなたのコードには '' * * ''がありますが、あなたの例では' '* +" 'があります。どちらをお探しですか? – jonhopkins

+0

これは練習ではなかったものです: 're.sub( '\ *(?*?)\ * \ +'、r '!\ 1 !!'、some_text)' –

答えて

0
>>> x = 'here is +some*+ text and also +some more*+ text here' 
>>> x = x.replace('*+','!!') 
>>> x 
'here is +some!! text and also +some more!! text here' 
>>> x = x.replace('+','!') 
>>> x 
'here is !some!! text and also !some more!! text here' 

replaceへの最後の引数はオプションです - あなたはそれを残せば、それは、単語のすべてのインスタンスを置き換えます。だから、より大きな部分文字列を最初に置き換えて、誤って小さなものを取り除いてから、小さなものに置き換えて使用してください。

-1

あなたが

関連する問題