2017-10-05 6 views
0

例のリストの中の文字を変更:は、文字列

eword_list = ["a", "is", "bus", "on", "the"] 
alter_the_list("A bus station is where a bus stops A train station is where a train stops On my desk I have a work station", word_list) 
print("1.", word_list) 

word_list = ["a", 'up', "you", "it", "on", "the", 'is'] 
alter_the_list("It is up to YOU", word_list) 
print("2.", word_list) 

word_list = ["easy", "come", "go"] 
alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_list) 

word_list = ["a", "is", "i", "on"] 
alter_the_list("", word_list) 
print("4.", word_list) 

word_list = ["a", "is", "i", "on", "the"] 
alter_the_list("May your coffee be strong and your Monday be short", word_list) 
print("5.", word_list) 

def alter_the_list(text, word_list): 
    return[text for text in word_list if text in word_list] 

私はテキストの文字列内の別の単語である単語のリストから任意の単語を削除しようとしています。単語のリストの要素がすべて小文字であることを確認する前に、文字列を小文字に変換する必要があります。テキストの文字列に句読点はなく、単語のパラメータリストの各単語は一意です。私はそれを修正する方法を知らない。

出力:期待

1. ['a', 'is', 'bus', 'on', 'the'] 
2. ['a', 'up', 'you', 'it', 'on', 'the', 'is'] 
3. ['easy', 'come', 'go'] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 

1. ['the'] 
2. ['a', 'on', 'the'] 
3. [] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 
+0

'リスト(セット(WORD_LIST) - セット(setence.lower()スプリット()。 ) '。 –

答えて

1

私はこのようにそれをやった:

def alter_the_list(text, word_list): 
    for word in text.lower().split(): 
     if word in word_list: 
      word_list.remove(word) 

text.lower().split()text内のすべてのスペースで区切られたトークンのリストを返します。

鍵は、あなたがに変更することです。word_listです。新しいlistを返すだけでは不十分です。インプレースのリストを変更するには、Python 3's list methodsを使用する必要があります。

0

あなたの主な問題は、関数から値を返してから無視することです。

word_list = ["easy", "come", "go"] 
word_out = alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_out) 

印刷したものは元の単語リストであり、機能結果ではありません。

あなたは関数にテキストパラメータを無視します。変数の名前をリストの理解のループインデックスとして再利用します。

return[word for word in word_list if word in word_list] 
など

あなたはまだあなたが構築リストのロジックで テキストが関与する必要があり、別の変数名を取得します。あなたは特定のテキストの中で ではない単語がではないことを忘れないでください。

ほとんどの場合、基本的なデバッグを学びます。 この素敵なdebugブログを参照してください。

他の場合は、printステートメントを使用して変数の値を表示し、プログラムの実行をトレースしてください。

解決策に向かって進むのですか?

1

結果のリストの順序は、あなたがセットを使用することができる問題ではない場合:

def alter_the_list(text, word_list): 
    word_list[:] = set(word_list).difference(text.lower().split()) 

この機能が原因私は好きword_list[:] = ...

+0

これは私が今までに見た中で最も速い編集とダウンボトムでなければなりません。 – mhawke

+0

さて、私はこれらの行為のうちのただ一つの責任しか負いません:-)私は実際にこれが有用な答えだと思っています。 +1 –

+0

@ChristianDean:編集してくれてありがとう:) – mhawke

0

と、リストスライスへの割り当てに代わってword_listを更新します@Simonさんは、より良い答えていますが、2つのリスト内包表記でそれをしたい場合:

def alter_the_list(text, word_list): 
    # Pull out all words found in the word list 
    c = [w for w in word_list for t in text.split() if t == w] 
    # Find the difference of the two lists 
    return [w for w in word_list if w not in c] 
+0

これは実際には1つのリスト内包で実行される可能性があります: '[setence.lower()。split()]'にない単語ならばword_listの単語です。かなり読める。 –