如何在python中将文本文件转换为字典

2024-10-02 12:29:25 发布

您现在位置: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)}

数据:

^{pr2}$

我需要帮助启动代码。到目前为止,我有一个代码,删除空白行,并将其列为一个列表。在

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

Tags: 数据代码字典格式linegreenmyfile球员
3条回答

下面是一个简单的方法:

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

我想这应该是你想要的:

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,如果解析失败,就把它当作名称处理。在

也许是这样的:

对于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

^{pr2}$

相关问题 更多 >

    热门问题