2011-12-04 29 views
3

"and"、 "as"、 "like"などの段落から特定の単語を削除したい。置き換え経由でそれを行うよりも、文字列から単語を削除する簡単な方法があります -Pythonの文字列置換方法の代わりに

new_str = str.replace(' and ', '').replace(' as ', '').replace(' like ', '') 

は、例えば、次のような方法がありますか?

str.remove([' and ', ' like ', ' as '])

答えて

6

はい、あなたはreモジュールからsub機能を使用することができます。

>>> import re 
>>> s = 'I like this as much as that' 
>>> re.sub('and|as|like', '', s) 
'I this much that' 
+3

を...しかし、あなたはについても、少しでも気にならばこの単純なルールであれば、正規表現では実行しません。 (これは、一般的なパフォーマンスについて心配する必要はありませんが、これは早すぎる最適化に関するステートメントが当てはまらない明白なケースです; 'str.replace'は' re.sub'よりも速いものであることが知られています)。 –

+0

@ChrisMorgan:非常に良い観察!私はそれについても考えましたが、OPは 'replace'以外の何かを言いましたので、私は別の(パフォーマンスが悪い)解決策を探すことを余儀なくされました – juliomalegria

1

あなたは正規表現を使用できます:あなたはまた、正規表現なしで行うことが

>>> import re 
    >>> test = "I like many words but replace some occasionally" 
    >>> to_substitute = "many|words|occasionally" 
    >>> re.sub(to_substitute, '', test) 
    'I like but replace some ' 
1

を。次の例にあなたが気にすべてが読みやすさと必ずしもパフォーマンスであれば、あなたはこのような何かができることを

def StringRemove(st,lst): 
    return ' '.join(x for x in st.split(' ') if x not in lst) 

>>> StringRemove("Python string Java is immutable, unlike C or C++ that would give you a performance benefit. So you can't change them in-place",['like', 'as', 'and']) 
"Python string Java is immutable, unlike C or C++ that would give you a performance benefit. So you can't change them in-place" 

>>> st="Python string Java is immutable,  unlike C or C++ that would give you a performance benefit. So you can't change them in-place" 
>>> StringRemove(st,['like', 'as', 'and'])==st 
True 
>>> 
+0

これは行内の複数のスペースを破壊し、' \ r'、 \ n'と '\ t'をスペースに挿入します。スペースを気にする人は 'st.split()'の代わりに 'st.split( '')'を使ってください。また、 'join()'本体の角括弧はきれいではありません。私はそれらをスクラップして、それをリストの理解の代わりにジェネレータの式にします(大きな入力の場合はメモリを少なくします)。 –

+0

指摘していただきありがとうございます。私は少しそれを微調整したので、今は複数のスペースや他の区切りで動作します。リストをジェネレータに変更しました。 – Abhijit

+0

あなたの変更により、タブと改行が単語セパレータとして機能しなくなりました。そのため、タブの後に単語があった場合などには削除されません。 –

0

注を参照してください:

new_str = str 
for word_to_remove in [' and ', ' as ', ' like ']: 
    new_str = new_str.replace(word_to_remove, '')