簡體   English   中英

讀取文本文件並存儲到字典中

[英]Read text file and store into dictionary

我試圖弄清楚將文件的內容存儲到特定鍵中的多個值中。

所需的輸出:

{'city1':[Island-1,Island-3],'city2':[Island-2,Island-4]}

data.txt中

city1-south:"London"
city1-south:"Paris"
city1-north:"Amsterdam"
city1-north:"Island-1"
city2-south:"Island-2"
city1-east:"Island-3"
city2-west:"Island-4"


def readFile(data_file):
    data = open(data_file,"r")
    d = {}
    for line in data:
        if 'Island' in line:
            city,loc = line.rstrip("\n").split(":",1)
            d[city] = loc
    print (d)
    data.close()

data_file = "data.txt"
readFile(data_file)

電流輸出:

{'city2-south': '"Island-2"', 'city2-west': '"Island-4"', 'city1-east': '"Island-3"', 'city1-north': '"Island-1"'}

我現在無法運行您的代碼,因為未定義config_file 我進行了一些修改,以便您的代碼可以運行。

with open("data.txt") as data:
    d = {'city1': [], 'city2': []}
    for line in data:
        if 'Island' in line:
            city,loc = line.rstrip("\n").split(":",1)
            for key in d.keys():
                if key in city:
                    d[key].append(loc[1:-1])
print(d)

結果:

{'city1': ['Island-1', 'Island-3'], 'city2': ['Island-2', 'Island-4']}

目前, Island-1等只能在字典中作為字符串輸出,因為否則python會將它們視為變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM