2016-06-28 219 views
0

我需要將不同長度的行轉換爲一個字典。這是玩家統計。文本文件格式如下。我需要返回一個字典與每個球員的統計。如何將文本文件轉換爲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() 
+3

是否需要使用該格式的文本文件?它可以改變的東西?這種格式不容易解析。 –

+0

用空白字符串替換逗號的方法在這裏不起作用。當然,這些行會轉換爲列表,但是您也可以刪除玩家統計信息中的逗號。 – DrNightmare

+0

是的文本文件必須是格式@MichaelPratt – Mia

回答

1

我想這應該做你想要什麼:

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來放鬆一點,如果它解析失敗,可以將它當作名稱來處理。

+0

你的意思是新玩家:'如果len(toks)== 1'。 'str.split'將永遠不會有長度爲0的輸出,即使是空字符串'''也會以一個索引返回(因此輸出長度爲1)。 –

+0

@ M.T對不起,修正。 – amaurea

1

這裏有一個簡單的方法來做到這一點:

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 
0

也許是這樣的:

對於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]))) 
相關問題