简体   繁体   English

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

[英]Python - How to pull certain information out of a string?

I'm working on a problem which consists of two programs. 我正在研究一个包含两个程序的问题。 The first program will write a worker's ID, hourly pay rate, and hours worked to a text file four times. 第一个程序将工人的ID,小时工资率和工作时间写入文本文件四次。 The second program will take the information entered from program #1's text file, display the worker's ID, and the worker's gross pay. 第二个程序将获取从程序#1的文本文件中输入的信息,显示工人的ID和工人的工资总额。

I've gotten the first program up and running, and the output is how it's supposed to be (the lab that this problem comes from gives you an example of how the output should look like) 我已经启动并运行了第一个程序,输出就是应该的样子(此问题来自的实验室为您提供了输出外观的示例)

Anyways, here's my code for the first program: 无论如何,这是我的第一个程序代码:

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()

Now my question is - how would I write a second program in order to convert each line back into their respective variables, so that I can use the hourly pay & hours worked to calculate gross pay? 现在我的问题是-我将如何编写第二个程序以将每行转换回各自的变量,以便可以使用小时工资和工作时间来计算总工资?

Use str.split() to break each line into a list, and unpack that list into variables: 使用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))

This assumes that the user will not enter any whitespace. 这假定用户将不会输入任何空格。 It also assumes that the same worker id is not entered more than once. 它还假定同一工人ID的输入不超过一次。

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

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