如何在python

时间:2016-06-28 19:50:58

标签: python list file dictionary text

我需要将不同长度的行转换为一个字典。这是玩家统计数据。文本文件的格式如下。我需要为每位玩家的统计数据返回一本字典。

{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 :(得分: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来放松一点,如果它无法解析则将其视为名称。

答案 1 :(得分: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

答案 2 :(得分: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])))