使用python

时间:2015-11-23 20:47:30

标签: python

编辑:已更新帖子以获得更清晰,没有答案尚未提供帮助!

好吧,所以我的任务是获取一个文本文件,每行有4个条目,分别是firstName,lastName,hours,payRate。我要做一些计算,并将所有这些信息放在python中的格式化表中。现在,我已经有了将数据输入到表中的代码,但它只适用于文本文件中的第一个条目,而我无法使其循环。老实说,我觉得自己像个白痴,这只是一个简单的修复。

我的输出应该是这样的:

http://i.imgur.com/bIOBqye.png

真的可以使用一些指针来完成这个循环并从文本文件的每一行打印数据。以下是我当前代码的外观:

heading1 = "{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",         "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay")
heading2=    "=============================================================================================================="

print(heading1)
print(heading2)

if os.path.isfile(fileQuestion) == True:
file = open('emps', 'r')
data = file.readlines()
for tmp in data:

    data2= [word.rstrip("\n") for word in data]
    first = data2[0].split()

    lastName = first[0]
    firstName = first[1]
    first[2]=(int(first[2]))
    first[3]=(int(first[3]))
    initialHours = first[2]
    payRate = first[3]

    if initialHours > 40:
        overHours = initialHours - 40
        regHours = 40
        regPay = payRate * regHours
        otPay = overHours * (payRate * 1.5)
        grossPay = regPay + otPay

    else:
        regHours = first[2]
        grossPay = initialHours * payRate
        overHours = 0



    heading3= "{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}   {5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay)
    heading4= "{0:15s}{1:21.2f}".format("Total Gross Pay", grossPay)
    heading5= "{0:15s}{1:19.2f}".format("Average Gross Pay", grossPay)
    heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", 33)
    spaceHeading = "               "

    print(heading3)
    print(spaceHeading)
print(heading4)
print(heading5)
print(heading6)

如果我没有正确地做任何事情,请在第一时间告诉我。感谢。

3 个答案:

答案 0 :(得分:0)

好吧,我想想,你可能想要data2 = [word.rstrip("\n") for word in tmp],但是没有看到样本输入和所需的输出,这很难说。

另外,

first[2]=(int(first[2]))
first[3]=(int(first[3]))
initialHours = first[2]
payRate = first[3]

可能是:

initialHours = int(first[2])
payRate = int(first[3])

但您还需要更改对first[2]

的其他引用

最后,我改变了

if os.path.isfile(fileQuestion) == True:
file = open('emps', 'r')
data = file.readlines()
for tmp in data:

为:

if os.path.isfile(fileQuestion) == True:
with open('emps', 'r') as myfile:
    for tmp in myfile:

这可确保文件正确关闭(您的代码不会将其关闭),并直接遍历文件,而不是使用readlines(),在执行其他操作之前不必要地将整个文件读取到内存中。请注意file是一个python builtin,所以变量名称选择不好。

答案 1 :(得分:0)

我找到了副本,并认为有些人对待粗鲁; /只是不关注程序员的实用问题,而是关注Stack的良好规则:(

以下是我对您的问题的完整答案:

1) 首先,您必须记住 ident 用于代替另一个版权所知的代码块括号。

我重新格式化了你的代码,记住当你把它放在这里时,所有的行都应该有一些额外的空格;)

2)就像说:

first = word.split()

修复循环中“不改变”的行。

3)总加班时间有硬编号:

heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", overHours)

此外,overHours(All?)不应该在'else'块循环中“归零”。你必须在循环之前初始化它。

我改变了一些其他的地方,即一些硬编码的整数,也许它不理想,并且你的风格,但你有我的修复下面的代码......

最好,如果您使用GitHub或Bitbucket或其他可通过网络访问的回购,因为您可以根据需要提供帮助,并且 - 您自己也可以找到所做的所有更改。然后,请在这里请求帮助解决极其未知的问题。在学习的乞讨中,总是很难找到,但后来 - 你可以获得更多!

以下是我的更改后的代码:

from os.path import isfile as isFileExsist
import sys

filePath = input("What is the name of your file?: ")

while isFileExsist(filePath) == False:
    pos = ['y', 'Y', 'yes', 'Yes']
    neg = ['n', 'N', 'no', 'No']
    answer = input("File not found! Do you want to start again? (y-yes/n-no)")
    if answer in neg:
        exit("Bye!")
    elif answer in pos:
        filePath = input("What is the name of your file?: ")
        continue
    else:
        print("Not sure what is the answer. Try again!")
        continue

file = open(filePath, 'r')
data = file.readlines()

print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",   "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay"))
print("==============================================================================================================")

overHoursAll = 0
grossPayAll = 0
count = 0

for line in data:
    words = line.split()

    lastName = words[0]
    firstName = words[1]
    initialHours=(int(words[2]))
    payRate =(int(words[3]))

    if initialHours > 40:
        regHours = 40
        overHours = initialHours - 40

        regPay = payRate * regHours
        otPay = overHours * (payRate * 1.5)
        grossPay = regPay + otPay
    else:
        regHours = initialHours
        overHours = 0

        grossPay = initialHours * payRate


    grossPayAll += grossPay
    overHoursAll += overHours

    # heading3
    print("{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}{5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay))
    # space heading
    print("               ")

# overall stats
print("{0:15s}{1:21.2f}".format("Total Gross Pay", grossPayAll))
print("{0:15s}{1:19.2f}".format("Average Gross Pay", grossPayAll / len(data)))
print("{0:15s}{1:16d}".format("Total Overtime Hours", overHoursAll))

致以诚挚的问候,对不起我的英语。

答案 2 :(得分:0)

import os.path
import sys
#fileQuestion = input("What is the name of your file?: ")
fileQuestion = "Testfile.txt"
heading1 = "{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",   "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay")
heading2=    "=============================================================================================================="

print(heading1)
print(heading2)

if os.path.isfile(fileQuestion) == True:
    file_handle = open(fileQuestion, 'r')
#file = open('emps', 'r')
#data = file.readlines()    I would't go for readline here

#file_handle2 = open('outupt.txt')
total_gross_pay = 0
number_of_employees = 0
average_gross_pay = 0
total_overtime = 0
standard_working_hours = 40

for i in file_handle:
    data = i.rstrip().lstrip().split()

    #print (data)
    first_name, last_name, hours, payrate = data

    hours = int(hours)
    payrate = int(payrate)
    basic_pay = hours * payrate

    if(hours > standard_working_hours):
        overtime = hours - standard_working_hours
        overtime_premium = overtime * payrate
        gross_pay = overtime_premium + basic_pay

    else:
        overtime = 0
        gross_pay = basic_pay

    total_overtime += overtime
    total_gross_pay += gross_pay
    number_of_employees += 1

    print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format(first_name, last_name, str(hours), str(payrate), str(overtime), str(gross_pay)))

print('\n')
print("Total Gross Pay:   ",total_gross_pay)
print("Average Gross Pay: ",total_gross_pay/number_of_employees)
print("Total overtime:    ",total_overtime)