2016-03-31 4 views
-4

1)に追加:は、テキストファイルを開くと、私は次のようにコロンで区切られた値でテキストファイルを開くために探していた辞書

名:ダニエル 年齢:12 性別:男性 ...

どのように私はPythonで、このテキストファイルを開いて、それがこのように終わるように辞書にすべてのものを追加します:

dictionary={"Name":"Daniel","Age":"12","Gender","male"...} 

2)私は、ユーザーがキーを検索できるようにしたいです、 「名前」と言い、プログラムを実行してみましょうtputs "ダニエル"。これどうやってするの?

+2

ドキュメントを読む... [ファイルを読み書き](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)と [辞書](https://docs.python.org/2/tutorial/datastructures.html#dictionari es) – ILostMySpoon

答えて

-1

そして、行間の区切り記号は何ですか?それが改行されている場合は、file.readlinesを行うことができます。

yourFile = open("file.txt", "r") 
lines = yourFile.readlines() 
output = {} 
for line in lines: 
    #BE CAREFUL! [-2] if window line break (\r\n) 
    #You can also do l = line.replace('\r', "").replace("\n", "") 
    #Which is better, because it is cross-platform and cross-format 
    l = line[-1] 
    output[l.split(':')[0]] = l.split(':')[1] 

説明:

  • yourFile.readlinesは、ファイルを読み込み、我々はのために、ループを行う["line1\n", "line2\n"]
  • のようにそれを返します
    • :我々は\ r \ nまたは\ rは、OSに依存!!それだけで\ n個にする必要がありますが、...各ラインのための
    • を試し、nは\(改行文字(複数可)をカット我々はsp列で点灯して文字列:"Name:Daniel".split(":")戻り['Name', 'Daniel']
    • 我々はそれが動作しますが、注意しなければなりませんdictionnary['key'] = 'value'構文

と辞書にそれを追加:コラム滞在の間スペース! それを削除するには、あなたがstring.replaceを使用する必要があります("Name : Daniel".replace(" ", "")意志を返す"Name:Daniel」)

とリターンの名前、あなたは辞書、単純に何も持っていたら:。。dictionnary["Name"]出力"Daniel"

-1

提案:

file = open("file.txt","r") 
output_dict={} 
lines=file.readlines() 
file.close() 
line=lines[0].replace(" : "," ") 
words=line.split(' ') 
for i in range(0,len(words)-1,2): 
    output_dict[words[i]]=words[i+1] 
print(output_dict) 
関連する問題