使用用户输入从csv文件中提取数据

时间:2017-12-04 23:57:27

标签: python csv input

我对Python很陌生,但我正在努力学习更多内容,而我自己创建的第一个迷你项目是创建一个代码,可以接收给定用户名的输入然后输出他们在某个项目上工作的小时数。我在本周末为我的部门和csv中的员工收到了一个csv我有他正在进行的各种项目以及专门用于该项目的时间。 csv文件的问题是该用户有重复的项目,所以当我的csv输出时,我需要它只显示一个项目名称和与该项目相关的所有小时数。如何让我的代码读取重复项,只计算重复项的小时数,只使用一个项目名称?

以下是我目前提出的代码:

import csv
with open('Report.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    firsts = []
    lasts = []
    projects = []
    hours = []
    for row in readCSV:
        first = row[0]
        last = row[1]
        project = row[2]
        hour = row[3]

        firsts.append(first)
        lasts.append(last)
        projects.append(project)
        hours.append(hour)

    First_name = input("Please enter the first name: ")
    First_1 = firsts.index(First_name)
    Last_1 = lasts[First_1]
    project_1 = projects[First_1]
    hours_1 = hours[First_1]
    print(First_1, Last_1, project_1, hours_1)

以下是csv

的示例
First   Last    Project             Hours
David   Ayers   AD-0002  Training   24
Oriana  Morfitt AD-0002  Training   24
David   Ayers   AD-0003  Personal Time  8
David   Ayers   AD-0004  Sick Time  0
Oriana  Morfitt AD-0005  Vacation   40
Sujatha Kavuri  Beeline Blank   29
Sujatha Kavuri  Beeline Blank   16
Sujatha Kavuri  OPS-0001 General Operational Support    6
Jeff    Moore   OPS-0001 General Operational Support    5
Sri Mantri  SRV-0001 Service Requests for Base and Direct Services  4
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  11
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  10
Jeff    Moore   SRV-0006 Standards and Processes    5
Jeff    Moore   SRV-0006 Standards and Processes    3
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   12.5
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   7
Jeff    Moore   0024495915 Work Instructions (infrastructure) - time tracking   1
Sri Mantri  0026184229 Margin Controlling Java Rewrite  4
Sujatha Kavuri  0029157489 SCRM Life Cycle Extension    3
Jeff    Moore   0031369443 Shopcall Attachment Changes  1
Jeff    Moore   0031500942 MP Strategy 2015 - Spot PO via EDI (time tracking only) - 0031500942 1

1 个答案:

答案 0 :(得分:2)

我敢打赌,有一种更好的方法可以用熊猫来做,但这也会有效:

import csv

# I've used full name to avoid duplicate first names in report 
full_name = input('Enter your full name: ')

with open('Report.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        if ' '.join((row[0], row[1])) == full_name.strip():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(row[3])

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

Sujatha Kavuri的结果

  

输入您的全名:Sujatha Kavuri
  这是Sujatha Kavuri整个小时的报告:
  直线空白:45小时
  OPS-0001一般操作支持:6小时

编辑 - 我只对文件的一半进行了采样,因此结果并不完整 希望这会有所帮助。