【问题标题】:Read records from CSV file and print report从 CSV 文件中读取记录并打印报告
【发布时间】:2020-05-08 08:08:33
【问题描述】:

我已经为一个程序工作了一周,但一直无法按照指南进行工作。

在这个程序(payroll.py)中,我必须打开 CSV 数据文件(employees.csv),读取文件中的记录,并生成一个使用 payroll.py 中的函数生成工资单报告。输出应打印写入单独的输出文件,最终应如下所示:

LastName    FirstName    Hours    RegHours    OTHours    RegPay    OTPay    GrossPay    Deductions    NetPay
Hightower   Michael      42.0     40.0        2.0        400.00    30.00    430.00      107.07        322.93
Jackson     Samuel       53.0     40.0        13.0       506.00    246.68   752.67      187.42        565.25
Jones       Catherine    35.0     35.0        0.00       680.05    0.00     680.05      169.33        510.72

工资单程序本身就可以正常工作(不调用 CSV 文件),但是当我尝试调用该文件(使用“from csv import reader”)时,会发生以下两种情况之一:

1) 我可以调用前三列(姓氏、名字和小时数),但我无法“插入”其他列(我得到一个索引错误,因为这些列当然没有存在于原始 CSV 文件中),或

2) 程序只提取一条完整的记录,恰好是 CSV 文件中的最后一条记录。

任何有关如何完成此操作的指导将不胜感激。谢谢。

这是 payroll.py 的代码:

def main() :
    employeeFirstName, employeeLastName = employeeFullName()
    employeePayRate, employeeHoursWorked = employeePay()
    employeeRegularHours, employeeOvertimeHours = calculateRegularHours(employeeHoursWorked)
    employeeOvertimeHours = calculateOvertimeHours(employeeHoursWorked)
    employeeTotalHours = calculateTotalHours(employeeRegularHours, employeeOvertimeHours)
    regularPayAmount = calculateRegularPay(employeePayRate, employeeRegularHours)
    overtimePayAmount = calculateOvertimePay(employeePayRate, employeeOvertimeHours)
    grossPayAmount = calculateGrossPay(regularPayAmount, overtimePayAmount)
    federalTaxWithheld = calculateFederalTax(grossPayAmount)
    stateTaxWithheld = calculateStateTax(grossPayAmount)
    medicareTaxWithheld = calculateMedicareTax(grossPayAmount)
    socSecTaxWithheld = calculateSocSecTax(grossPayAmount)
    totalTaxesWithheld = calculateTotalTaxes(federalTaxWithheld, stateTaxWithheld, medicareTaxWithheld, socSecTaxWithheld)
    netPayAmount = calculateNetPay(grossPayAmount, totalTaxesWithheld)
    payrollSummaryReport(employeeFirstName, employeeLastName, employeePayRate, employeeRegularHours, employeeOvertimeHours, employeeTotalHours, regularPayAmount, overtimePayAmount, grossPayAmount, federalTaxWithheld, stateTaxWithheld, medicareTaxWithheld, socSecTaxWithheld, totalTaxesWithheld, netPayAmount)

def employeeFullName() :
    employeeFirstName = str(input("Enter the employee's first name: "))
    employeeLastName = str(input("Enter the employee's last name: "))
    return employeeFirstName, employeeLastName

def employeePay() :
    employeePayRate = float(input("Enter the employee's hourly pay rate: "))
    employeeHoursWorked = float(input("Enter the employee's hours worked: "))
    return employeePayRate, employeeHoursWorked

def calculateRegularHours(employeeHoursWorked) :
    if employeeHoursWorked < 40 :
        employeeRegularHours = employeeHoursWorked
        employeeOvertimeHours = 0

    else:
        employeeRegularHours = 40
        employeeOvertimeHours = employeeHoursWorked - 40

    return employeeRegularHours, employeeOvertimeHours

def calculateOvertimeHours(employeeHoursWorked) :
    if employeeHoursWorked > 40 :
        employeeOvertimeHours = employeeHoursWorked - 40

    else :
        employeeOvertimeHours = 0

    return employeeOvertimeHours

def calculateTotalHours(employeeRegularHours, employeeOvertimeHours) :
    employeeTotalHours = employeeRegularHours + employeeOvertimeHours
    return employeeTotalHours

def calculateRegularPay(employeePayRate, employeeHoursWorked) :
    regularPayAmount = employeePayRate * employeeHoursWorked
    return regularPayAmount

def calculateOvertimePay(employeePayRate, employeeOvertimeHours) :
    overtimePayRate = 1.5
    overtimePayAmount = (employeePayRate * employeeOvertimeHours) * overtimePayRate
    return overtimePayAmount

def calculateGrossPay(regularPayAmount, overtimePayAmount) :
    grossPayAmount = regularPayAmount + overtimePayAmount
    return grossPayAmount

def calculateFederalTax(grossPayAmount) :
    federalTaxRate = 0.124
    federalTaxWithheld = grossPayAmount * federalTaxRate
    return federalTaxWithheld

def calculateStateTax(grossPayAmount) :
    stateTaxRate = 0.049
    stateTaxWithheld = grossPayAmount * stateTaxRate
    return stateTaxWithheld

def calculateMedicareTax(grossPayAmount) :
    medicareTaxRate = 0.014
    medicareTaxWithheld = grossPayAmount * medicareTaxRate
    return medicareTaxWithheld

def calculateSocSecTax(grossPayAmount) :
    socSecTaxRate = 0.062
    socSecTaxWithheld = grossPayAmount * socSecTaxRate
    return socSecTaxWithheld

def calculateTotalTaxes(federalTaxWithheld, stateTaxWithheld, medicareTaxWithheld, socSecTaxWithheld) :
    totalTaxesWithheld = federalTaxWithheld + stateTaxWithheld + medicareTaxWithheld + socSecTaxWithheld
    return totalTaxesWithheld

def calculateNetPay(grossPayAmount, totalTaxesWithheld) :
    netPayAmount = grossPayAmount - totalTaxesWithheld
    return netPayAmount

def payrollSummaryReport(employeeFirstName, employeeLastName, employeePayRate, employeeRegularHours, employeeOvertimeHours, employeeTotalHours, regularPayAmount, overtimePayAmount, grossPayAmount, federalTaxWithheld, stateTaxWithheld, medicareTaxWithheld, socSecTaxWithheld, totalTaxesWithheld, netPayAmount) :
    print()
    print("\t\t\t\t\t\tPayroll Summary Report")
    print()
    print("%-12s%-12s%-8s%-10s%-10s%-12s%-10s%-11s%-13s%-10s" % ("LastName", "FirstName", "Hours", "RegHours", "OTHours", "RegPay", "OTPay", "GrossPay", "Deductions", "NetPay"))
    print("%-12s%-12s%-8.2f%-10.2f%-10.2f$%-11.2f$%-9.2f$%-10.2f$%-12.2f$%-10.2f" % (employeeLastName, employeeFirstName, employeeTotalHours, employeeRegularHours, employeeOvertimeHours, regularPayAmount, overtimePayAmount, grossPayAmount, totalTaxesWithheld, netPayAmount))

main ()

我需要使用的 CSV 文件 (employees.csv) 如下所示:

First,Last,Hours,Pay
Matthew,Hightower,42,10
Samuel,Jackson,53,12.65
Catherine,Jones,35,19.43
Charlton,Heston,52,10
Karen,Black,40,12
Sid,Caesar,38,15
George,Kennedy,25,35
Linda,Blair,42,18.6
Beverly,Garland,63,10
Jerry,Stiller,52,15
Efrem,Zimbalist,34,16
Linda,Harrison,24,14
Erik,Estrada,41,15.5
Myrna,Loy,40,14.23

【问题讨论】:

  • 只是为了澄清我需要弄清楚的:
  • 一个循环,打开 CSV 文件 (employees.csv) 并读取每个员工/行,从工资核算函数(来自 payroll.py)执行计算,然后在 "表”格式(如我原来的帖子所示)。

标签: python-3.x


【解决方案1】:

您可以将.csv 文件视为普通文件。不需要reader。这是一个可能处理您的文件的函数:

 def get_data(fname):
  ''' 
    Function returns the dictionary with following 
    format:
    { 0 : {
        "fname": "...",
        "lname": "...",
        "gross": "...",
      },
      1 : {
        ....,
        ,,,,
      },
    }
  '''
  result = {} # return value 
  i = 0 # you can zip range() if you want to
  with open(fname, 'r') as f: 
    for line in f.readlines()[1:]:
      result[i] = {}
      tmp = line.split(",") # list of values from file 
      # access file values by their index, e.g. 
      # tmp[0] -> first name
      # tmp[1] -> last name
      # tmp[2] -> hours
      # tmp[3] -> pay rate

      # do calculations using your functions (calculateOvertimePay,
      # calculateTotalHours, etc.) and store the results in dictionary
      # e.g: 
      result[i]["fname"] = tmp[0]
      result[i]["lname"] = tmp[1]
      # ...
      # do calculations for report
      # ...
      # result[i]["regular"] = calc...(....)
      # result[i]["overtime"] = calc...(....)
      result[i]["gross"] = calculateGrossPay(result[i]["regular"], result[i]["overtime"])
      i += 1
    return result

您可能希望对 payrollSummaryReport(...) 函数做几件事来改进它:

  • dictlist 替换你庞大的参数列表
  • 稍微修改一下以满足您的要求

您可以通过这种方式进行改进:

def payrollSummaryReport(vals) :
    print()
    print("\t\t\t\t\t\tPayroll Summary Report")
    print()
    print("%-12s%-12s%-8s%-10s%-10s%-12s%-10s%-11s%-13s%-10s" %\
     ("LastName", "FirstName", "Hours", "RegHours", "OTHours", "RegPay", "OTPay", "GrossPay", "Deductions", "NetPay"))
    for i in vals:
      print("%-12s%-12s%-8.2f%-10.2f%-10.2f$%-11.2f$%-9.2f$%-10.2f$%-12.2f$%-10.2f" %\
       (vals[i]["fname"], vals[i]["lname"], vals[i]["gross"], ''' repeat for all fields '''))

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2019-04-29
    • 2021-04-02
    • 2023-04-09
    相关资源
    最近更新 更多