2016-04-17 18 views
-1

ファイルからリストにテキストを読み込み、分割関数を使って単語のリストに分割するプログラムを作成しています。そして、各単語については、すでにリストに入っているかどうかを確認する必要があります。そうでない場合は、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 
+0

を言うならば、[] [open('remeo.txt).read().split() ]

から削除すでにリストを返しますopen('remeo.txt).read().split()声明入力リストと出力リストの両方に対して 'word_list'を実行し、' [open( 'romeo.txt')。read()。split()] 'でリストの中にリストを作ります。これを行う最も効率的な方法は、 'set'を使うことですが、あなたは宿題をしていると思います。リストを使うだけです。また、ファイルを開くために 'with'を使う方法も学ぶべきです。 –

+0

"open( 'remeo.txt).read()。split()"はすでにリストを返していますので、 "[' open(' remeo.txt).read()。split()] " – pitaside

答えて

0

2つの別々の変数を使用してください。

word_list = [] 
word_list2 = open('romeo.txt').read().split() 
for item in word_list2: 
    if item in word_list: 
     continue 
    else: 
     word_list.append(item) 
word_list.sort() 
print word_list 

itemword_listからであるため、常にtrueになりますあなたがif item in word_list:をチェックしている瞬間、時:また、str.split()ので、リストその周り[]を置く必要はありませんが返されます。 itemを別のリストから繰り返します。

+0

助けてくれてありがとう!私はPythonには新しく、これは非常に役に立ちます。 – Chandra

+0

@Chandra問題ありません!答えを受け入れるようにしてください! – TerryA

0

削除カッコ

word_list = open('romeo.txt').read().split() 
0

スプリットはリストを返すので、必要はopen...splitの周りに角括弧をつけないように。順番は関係ない場合は順序が重要ならば、あなたがしたい場合は、それは、その後、

uniq_words = [] 
for word in open('romeo.txt').read().split(): 
    if word not in uniq_words: 
     uniq_words.append(word) 

1ライナー

uniq_words = set(open('romeo.txt').read().split()) 

word_list = sorted(set(open('romeo.txt').read().split())) 
print word_list 
0

:重複を削除するには、セットを使用しますソートして、最初のアプローチをとり、sorted()を使用します。

0

のでTerryAはあなたが2つの別々のリストを操作する必要がある、と言いますが、あなたのコードが使用しているように私は

word = "Hello\nPeter" 
s_word = [word.split()] # print [['Hello', wPeter']] 
But 
s_word = word.split() # print ['Hello', wPeter'] 
関連する問題