【问题标题】:Python: Effective reading from a file using csv modulePython:使用 csv 模块从文件中有效读取
【发布时间】:2015-01-24 05:25:02
【问题描述】:

我最近才开始学习 csv 模块。假设我们有这个 CSV 文件:

John,Jeff,Judy,
21,19,32,
178,182,169,
85,74,57,

我们想要读取这个文件并创建一个字典,其中包含名称(作为键)和每列的总数(作为值)。所以在这种情况下,我们最终会得到:

d = {"John" : 284, "Jeff" : 275, "Judy" : 258}

所以我编写了这段代码,它显然运行良好,但我对它不满意,想知道是否有人知道更好或更高效/优雅的方法。因为那里的行太多了:D(或者也许我们可以概括一下 - 即我们不知道那里有多少字段。)

d = {}
import csv
with open("file.csv") as f:
    readObject = csv.reader(f)

    totals0 = 0
    totals1 = 0
    totals2 = 0
    totals3 = 0

    currentRowTotal = 0
    for row in readObject:
        currentRowTotal += 1
        if currentRowTotal == 1:
            continue

        totals0 += int(row[0])
        totals1 += int(row[1])
        totals2 += int(row[2])
        if row[3] == "":
            totals3 += 0

f.close()

with open(filename) as f:
    readObject = csv.reader(f)
    currentRow = 0
    for row in readObject:   
        while currentRow <= 0:
            d.update({row[0] : totals0}) 
            d.update({row[1] : totals1}) 
            d.update({row[2] : totals2})
            d.update({row[3] : totals3}) 
            currentRow += 1
    return(d)
f.close()

非常感谢您的任何回答:)

【问题讨论】:

    标签: python file csv text


    【解决方案1】:

    使用第一行找出列标题是什么。根据标题初始化总计字典。

    import csv
    
    with open("file.csv") as f:
      reader = csv.reader(f)
    
      titles = next(reader)
      while titles[-1] == '':
        titles.pop()
      num_titles = len(titles)      
      totals = { title: 0 for title in titles }
    
      for row in reader:
        for i in range(num_titles):
          totals[titles[i]] += int(row[i])
    
    print(totals)
    

    让我补充一点,您不必在 with 块之后关闭文件。 with 的全部意义在于它负责关闭文件。

    另外,让我提一下,您发布的数据似乎有四列:

    John,Jeff,Judy,
    21,19,32,
    178,182,169,
    85,74,57,
    

    这就是我这样做的原因:

      while titles[-1] == '':
        titles.pop()
    

    【讨论】:

      【解决方案2】:

      有点脏,但试试这个(在没有空最后一列的情况下操作):

      #!/usr/bin/python
      
      import csv
      import numpy
      
      with open("file.csv") as f:
          reader = csv.reader(f)
          headers = next(reader)
      
          sums = reduce(numpy.add, [map(int,x) for x in reader], [0]*len(headers))
          for name, total in zip(headers,sums):
              print("{}'s total is {}".format(name,total))
      

      【讨论】:

        【解决方案3】:

        不确定是否可以使用 pandas,但可以按如下方式获取 dict:

        import pandas as pd
        df = pd.read_csv('data.csv')
        print(dict(df.sum()))
        

        给予:

        {'Jeff': 275, 'Judy': 258, 'John': 284}
        

        【讨论】:

          【解决方案4】:

          基于 Michasel 的解决方案,我会尝试使用更少的代码和更少的变量,并且不依赖于 Numpy

          import csv
          
          with open("so.csv") as f:
            reader = csv.reader(f)
            titles = next(reader)
            sum_result = reduce(lambda x,y: [ int(a)+int(b) for a,b in zip(x,y)], list(reader))
          
            print dict(zip(titles, sum_result))
          

          【讨论】:

            猜你喜欢
            • 2017-12-07
            • 2013-05-06
            • 1970-01-01
            • 2016-06-15
            • 2020-06-12
            • 2016-02-03
            相关资源
            最近更新 更多