【问题标题】:Python - How to pull certain information out of a string?Python - 如何从字符串中提取某些信息?
【发布时间】:2016-12-10 22:27:40
【问题描述】:

我正在处理一个由两个程序组成的问题。第一个程序会将工人的 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()

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

【问题讨论】:

  • 考虑通过添加逗号之类的分隔符来分隔字段,让自己的生活更轻松。这将更容易分隔值,尤其是在字段包含空格时。

标签: python file loops


【解决方案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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    相关资源
    最近更新 更多