2017-10-14 6 views
1

私のプログラムは、入力文にnotが続き、その後にbadが含まれているかどうかを調べ、goodに置き換えます。例えば文がnotbad内の他の文字列なしnot badが含まれている場合、私は以下のコードで与えられるgoodに置き換えることができた:特定の文字列がセンテンスに存在するかどうかを確認し、Python 3.6を使用して別の文字列で置き換えます。

s = 'The day is not bad' 
s = s.replace('not bad', 'good') 
print(s) 

出力は次の通りであった:

>>> The day is good 

badの間に他の単語がある場合に問題が発生します。 は、私が試したコードを見てください:

l = ['not', 'bad'] 
s = 'The day is not so bad' 
if l in s: 
    s = s.replace(l,'good') 

予想される出力はThe day is goodにする必要がありながら、それは次のようなエラーがthrowed:

Traceback (most recent call last): 

    File "<ipython-input-69-0eb430659d1e>", line 3, in <module> 
    if l in s: 

TypeError: 'in <string>' requires string as left operand, not list 

私もこのような何かを試してみました:

list_ = ['not', 'bad'] 
if any(word in 'The day is not at all bad' for word in list_): 
s = s.replace(s,'good') 

しかし、私が上記のコードで得たエラー出力は次のとおりです。

>>> s 
>>> good 

IOWでは、文全体がgoodに置き換えられました。 は、私は以下のような何かを得る必要がある場合はどうすべきかを提案することができ:

>>> s = 'The day is not at all bad' #input 

>>> print(output) 
>>> 'The day is good' # the desired output 
+1

最終的に私は何をしたい、私は私の答えを更新したしまった、確認してください。 –

答えて

1

あなたはこのに近づく可能性がいくつかの方法があります。 1つの方法は、文を単語のリストに変換し、リストに「not」と「bad」を見つけてそれらの間のすべての要素を削除し、次に「good」を挿入することです。

>>> s = 'the day is not at all bad' 
>>> start, stop = 'not', 'bad' 
>>> words = s.split() 
>>> words 
['the', 'day', 'is', 'not', 'at', 'all', 'bad'] 
>>> words.index(start) 
3 
>>> words.index(stop) 
6 
>>> del words[3:7] # add 1 to stop index to delete "bad" 
>>> words 
['the', 'day', 'is'] 
>>> words.insert(3, 'good') 
>>> words 
['the', 'day', 'is', 'good'] 
>>> output = ' '.join(words) 
>>> print(output) 
the day is good 

別の方法は、「悪い」に続いて、ゼロ以上の単語に続く「しない」と一致するパターンを見つけるためにregular expressionsを使用することです。 re.sub関数は、与えられたパターンに一致する文字列を検索し、指定した文字列に置き換えます:

>>> import re 
>>> pattern = r'not\w+bad' 
>>> re.search(pattern, s) 
>>> pattern = r'not(\s+\w+)* bad' # pattern matches "not <words> bad" 
>>> re.sub(pattern, 'good', s) 
'the day is good' 
2
import re 
s = 'The day is at not all bad' 
pattern=r'(not)(?(1).+(bad))' 

match=re.search(pattern,s) 

new_string=re.sub(pattern,"good",s) 

print(new_string) 

出力:

The day is at good 

正規表現の説明:

私が使用しましたif else条件正規表現はこちら:

;これは命題Aが真であれば、その後、パターンXと一致する」という意味

(condition1)(?(1)(do something else)) 
(?(A)X|Y) 

:どのように正規表現の作品にif else、他の正規表現構文た場合も、これは非常に単純である

それ以外の場合は、マッチパターンY.」この正規表現でとても

:文字列で、条件は、文字列に提示しなければならない 『ではない』です 『ない』場合

(not)(?(1).+(bad)) 

それが悪い "と一致します。

第二の正規表現: '悪い' マッチングされ、このグループ(2)では

(not.+)(bad) 

:あなたはまた、この正規表現を使用することができますしたい場合

あなたの文字列:

>>> s = 'The day is not at all bad' #input 

>>> print(output) 
>>> 'The day is good' # output 
+0

「bad」*の後に*「not」という単語を探しているこのアドレスは...あなたのdictの例では、置き換える前に文字列をチェックしているのはなぜですか?ただ試して置き換えてください。存在しない場合は何も起こりません... '' s'を2回スキャンしてもあまり意味はありません... –

関連する問題