簡體   English   中英

如何在python中將文本文件轉換為字典

[英]how to convert text file to dictionary in python

我需要將不同長度的行轉換為一本字典。 這是針對球員的數據。 文本文件的格式如下。 我需要返回一本包含每個玩家數據的字典。

{Lebron James:(25,7,1),(34,5,6), Stephen Curry: (25,7,1),(34,5,6), Draymond Green: (25,7,1),(34,5,6)}

數據:

Lebron James

25,7,1

34,5,6

Stephen Curry

25,7,1

34,5,6

Draymond Green

25,7,1

34,5,6

我需要啟動代碼的幫助。 到目前為止,我有一個刪除空白行並使這些行成為列表的代碼。

myfile = open("stats.txt","r") 
for line in myfile.readlines():  
    if line.rstrip():
         line = line.replace(",","")       
         line = line.split()

我認為這應該做您想要的:

data = {}
with open("myfile.txt","r") as f:
    for line in f:
        # Skip empty lines
        line = line.rstrip()
        if len(line) == 0: continue
        toks = line.split(",")
        if len(toks) == 1:
            # New player, assumed to have no commas in name
            player = toks[0]
            data[player] = []
        elif len(toks) == 3:
            data[player].append(tuple([int(tok) for tok in toks]))
        else: raise ValueErorr # or something

格式有些模棱兩可,因此我們必須對名稱可以做些假設。 我假設名稱不能在此處包含逗號,但是如果需要,可以嘗試解析int,int,int,然后放慢一點,如果解析失敗,則將其視為名稱,可以放寬一點。

這是執行此操作的一種簡單方法:

scores = {}

with open('stats.txt', 'r') as infile:

    i = 0

    for line in infile.readlines():

        if line.rstrip():

             if i%3!=0:

                 t = tuple(int(n) for n in line.split(","))
                 j = j+1

                 if j==1:
                    score1 = t # save for the next step

                 if j==2:
                    score  = (score1,t) # finalize tuple

              scores.update({name:score}) # add to dictionary

         else:

            name = line[0:-1] # trim \n and save the key
            j = 0 # start over

         i=i+1 #increase counter

print scores

也許是這樣的:

對於Python 2.x

myfile = open("stats.txt","r") 

lines = filter(None, (line.rstrip() for line in myfile))
dictionary = dict(zip(lines[0::3], zip(lines[1::3], lines[2::3])))

對於Python 3.x

myfile = open("stats.txt","r") 

lines = list(filter(None, (line.rstrip() for line in myfile)))
dictionary = dict(zip(lines[0::3], zip(lines[1::3], lines[2::3])))

暫無
暫無

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

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