ファイルからリストにテキストを読み込み、分割関数を使って単語のリストに分割するプログラムを作成しています。そして、各単語については、すでにリストに入っているかどうかを確認する必要があります。そうでない場合は、append関数を使用してリストに追加する必要があります。Pythonはファイルからリストに単語を追加します
所望の出力は次のようになります。
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
私の出力は、次のとおりです。私は初めに「[[&]]」でソートし、二重の角括弧を削除しようとしている
[['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks', 'It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun', 'Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon', 'Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']]
私はそうすることができません。そして、何らかの理由でsort()関数がうまくいかないようです。
私は間違いをどこにしているか教えてください。
word_list = []
word_list = [open('romeo.txt').read().split()]
for item in word_list:
if item in word_list:
continue
else:
word_list.append(item)
word_list.sort()
print word_list
を言うならば、[]
[open('remeo.txt).read().split() ]
から削除すでにリストを返します
open('remeo.txt).read().split()
声明入力リストと出力リストの両方に対して 'word_list'を実行し、' [open( 'romeo.txt')。read()。split()] 'でリストの中にリストを作ります。これを行う最も効率的な方法は、 'set'を使うことですが、あなたは宿題をしていると思います。リストを使うだけです。また、ファイルを開くために 'with'を使う方法も学ぶべきです。 –"open( 'remeo.txt).read()。split()"はすでにリストを返していますので、 "[' open(' remeo.txt).read()。split()] " – pitaside