简体   繁体   English

每行文本文件的目标单词和整数

[英]Targeting words and integers per line text file

For my code, i need to input a text file where each line will read a Last Name, Wage, and Hours worked . 对于我的代码,我需要输入一个文本文件,其中每行将读取一个姓氏,工资和工作时间 Each separated by a single whitespace character. 每个字符都由一个空格字符分隔。

Example: 例:

johnson 14 52 doe 12.12 35.5 smith 14.56 42

Further i have to print a report using these values until there are no more lines to take data from. 此外,我必须使用这些值打印报告,直到没有更多行可以提取数据为止。

I want to be able to assign the name to a variable(last) , the wage to a variable(rate) , and the hours worked to a variable(totalHours) and then use these variables to compute other things. 我希望能够将name to a variable(last)分配给name to a variable(last) ,将wage to a variable(rate) ,并将hours worked to a variable(totalHours) ,然后使用这些变量来计算其他内容。

But i cant figure out how to target each specific name, rate, and hours worked, for each line. 但是我无法弄清楚如何针对每行指定每个特定的名称,费率和工作时间。

Here's the code i have so far. 这是我到目前为止的代码。

f = open('test.txt', 'r')

for line in f:
    data = line.split()
       for word in data:
          last = 
          rate =
          totalHours =

   #these are my computations
    otHours = 0
    if totalHours > 40:
         otHours = totalHours - 40   
    regPay = (totalHours - otHours) * rate
    otPay = 1.5 * rate * otHours
    gross = regPay + otPay
    print("%-21s%-15.2f%-17.1f%-15.1f%-15.2f%-16.2f%3.2f" % \
       (last, rate, totalHours, otHours, regPay, otPay, gross))
f.close    

Any help is appreciated. 任何帮助表示赞赏。

You can unpack the data list, like below: 您可以解压缩data列表,如下所示:

last,rate,totalHours = data

Or, 要么,

last = data[0]
rate=data[1]
totalHours=data[2]

You can simply use 您可以简单地使用

 for line in f:
     last, rate, totalHours = line.split()

But there's another problem with your code. 但是您的代码还有另一个问题。 All these items will be read as strings. 所有这些项目将被读取为字符串。 You'll have to convert rate and totalHours to floats before doing any calculations with them. 在对它们进行任何计算之前,必须将ratetotalHours转换rate totalHours

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM