2017-12-20 13 views
1

私は次のようなテキストを持っています。Pythonで文字列を小文字に変換する簡単な方法

mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday" 

私はそれで_ABBを持っている言葉以外、小文字に変換します。

私の出力は次のようになります。

mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday" 

私の現在のコードは以下の通りです。

ただし、これを行うには簡単な方法があるかどうかを知りたいと思いますか?

+1

確かに、これについては1つのライナーを発明することができますが、あなたのバージョンには正確に何が間違っていますか?はるかに読みやすくなっています。 – Kendas

+1

@Kendas私はそう言っていないだろう。誰もその仕事のために多くのコードを見ることを期待しません。あまりにも多くの変数を作成する –

+0

'mytext.replace(" _ ABB "、" _ abb ")' – dsgdfg

答えて

11

あなたは、単語に文字列を分割する1つのライナーを使用str.endswith()と単語をチェックして、一緒に戻って言葉に参加することができます。もちろん

' '.join(w if w.endswith('_ABB') else w.lower() for w in mytext.split()) 
# 'this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday' 

'_ABB'が実際に発生する可能性があればinオペレータではなくstr.endswith()を使用言葉のどこにでも、最後にはありません。

+1

質問が質問するので、 '' '_ABB ' "それに_ABBを持つ言葉"。それは最後にある必要はありません – LcdDrm

+0

まだ私はそれが '_ABB 'で書かれていたので、それはOPが要求したものに適用されます。 – Adelin

3

拡張正規表現アプローチ:

import re 

mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday" 
result = re.sub(r'\b((?!_ABB)\S)+\b', lambda m: m.group().lower(), mytext) 

print(result) 

出力:

this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday 

詳細:

  • \b - ワード境界
  • (?!_ABB) - 先読み負の主張、与えられたパターンが
  • \S一致しないことが保証される - 非空白文字
  • \b((?!_ABB)\S)+\bを - 全体のパターンは、ここでサブ_ABB
0

を含まない単語が別の可能一致しました(エレガントではない)ワンライナー:

mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday" 

print(' '.join(map(lambda x : x if '_ABB' in x else x.lower(), mytext.split()))) 

どの出力:

this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday 

注:これは、テキストのみのスペースで単語を区切るになることを想定し、そのsplit()がここにいればよいです。テキストに",!."などの句読点が含まれている場合は、代わりに正規表現を使用して単語を分割する必要があります。

関連する問題