2016-11-29 3 views
-3

私は読書のためにファイルを開いており、私は各行を分析したい。行が条件を満たす場合は、その行を辞書に追加したいと思います。しかし、このコードは空のリストを返し続けます!間違っていることを指摘できますか?テキストファイルの行から辞書を作成しようとしていますが、コードは空の辞書を返し続けますか?

dictionary = {} 
file = open("text_file.txt", "r") 

colors = ("Bright red", "Light green", "Sky blue", "Dark brown") 

def read_file(file): 
    for line in file: 
     if line in colors: 
      dictionary[line] = '' 
return dictionary 
file.close() 

ときI入力:代わりに{'Bright red': '', 'Light green': '', 'Sky blue': '', 'Dark brown': ''}のように見えるの辞書を作成する

read_file(file) 

、それは{}を返します。

ファイルはテキストファイルであり、それは次のようになります。

各行の最初の単語のそれぞれが強調されている理由
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Bright red 
Aliquam et magna at orci lobortis blandit. 
Phasellus mattis velit auctor libero rhoncus semper. 
Curabitur vitae sapien ac sem lobortis egestas. 
Light green 
Sed vitae augue sit amet lectus consectetur consectetur. 
Sed bibendum metus vel libero porta, eu malesuada nibh mattis. 
Sky blue 
Dark brown 

わからない...しかし、それはテキストファイルは次のようになります。

私はPythonには本当に新しいので、簡単に私に行ってください。

+1

'return dictionary'は、関数内で私たちを見せているものですか? – MooingRawr

+0

この質問に誰が投票したのか分かりません。誰かが眠っている間にその人を使っているように見える –

+0

ファイルの一部と期待する出力を表示することができます – ettanany

答えて

1
  1. return dictionaryを削除する - あなたはそれを期待するときのステートメントは、おそらくtrueを返すされていない場合、それは意味
  2. ザ・を行うものではありません。あなたのループの中にある各行を印刷してみてください。\ n文字が混乱していますか?ファイル内

    dictionary = {} 
    file = open("text_file.txt", "r") 
    
    colors = ("Bright red", "Light green", "Sky blue", "Dark brown") 
    
    for line in file: 
        if line[0:-1] in colors: 
         dictionary[line] = "" 
    file.close() 
    

    あなたのラインが'line\n'次のとおりです。私はあなたがこのような何かをしなければならないと思いますfile.read().splitlines()代わりのfile

0

を反復処理してみてください。

'line\n' != 'line' 
+0

'dictionary [line] = line'についてあなたは確かですか?この行は意味をなさない。 –

+0

実際、はい、間違いです。 –

+0

dictionary [line] = '' –