Python - 如何从字符串中提取某些信息?

时间:2016-12-10 22:27:41

标签: python file loops

我正在研究一个由两个程序组成的问题。第一个程序会将工人的ID,每小时工资率和工作时数写入文本文件四次。第二个程序将从程序#1的文本文件中输入信息,显示工人的ID和工人的总工资。

我已经启动并运行了第一个程序,输出是它应该是什么样的(这个问题来自的实验室为您提供了输出应该如何的示例)

无论如何,这是第一个程序的代码:

def main():
  output_file = open ('workers.txt', 'w')
  count = 0
  while count <= 3:
      id = input("Enter worker ID: ")
      rate = input("Enter hourly payrate: ")
      hours = input("Enter number of work hours: ")
      output_file.write(id + ' ')
      output_file.write(rate + ' ')
      output_file.write(hours + '\n')
      count = count + 1
  output_file.close()

  read_file = open ('workers.txt', 'r')
  empty_str = ''
  line = read_file.readline()
  while line != empty_str:
      print(line)
      line = read_file.readline()
  read_file.close()
main()

现在我的问题是 - 如何编写第二个程序,以便将每一行转换回各自的变量,这样我就可以使用每小时付费&amp;工作时间来计算总工资?

1 个答案:

答案 0 :(得分:1)

使用str.split()将每一行分成一个列表,并将该列表解压缩为变量:

with open('workers.txt') as f:
    for line in f:
        worker_id, rate, hours = line.split()
        gross_pay = float(rate) * float(hours)
        print('ID: {}, gross pay: {:.2f}'.format(worker_id, gross_pay))

这假设用户不会输入任何空格。它还假定不会多次输入相同的工作者ID。

相关问题