【问题标题】:how to convert text file to dictionary in python如何在python中将文本文件转换为字典
【发布时间】:2016-10-31 07:22:25
【问题描述】:

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

{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()

【问题讨论】:

  • 文本文件是否需要采用该格式,或者是否可以更改?这种格式不太容易解析。
  • 您用空白字符串替换逗号的方法在这里不起作用。当然,这些行将被转换为一个列表,但您也可以删除玩家统计数据中的逗号。
  • 是的,文本文件必须采用该格式@MichaelPratt

标签: python list file dictionary text


【解决方案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 并在解析失败时将其视为名称来放松这一点。

【讨论】:

  • 你的意思是新玩家:if len(toks)==1str.split 永远不会有长度为 0 的输出,即使是空字符串 '' 也将作为具有一个索引的列表返回(因此输出长度为 1)。
  • @M.T 抱歉,已修复。
【解决方案2】:

这是一个简单的方法:

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

【讨论】:

    【解决方案3】:

    可能是这样的:

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

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2020-12-16
      • 2023-03-15
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      相关资源
      最近更新 更多