【问题标题】:How can I read from a file while differentiating the variables?如何在区分变量的同时从文件中读取?
【发布时间】:2019-07-22 18:52:41
【问题描述】:

我刚开始学习 Python,我有一些不知道如何开始的作业。

我必须从 (txt) 文件中读取有关公司员工的信息:name, age, occupation, salary, years_in_the company。它们位于不同的行中,并由选项卡分隔,例如:

Helen   20  Network Designer    5449    9
Jasmine 40  Software Architect  2536    1
Phoebe  28  Software Engineer   2627    7
Aysha   34  Software Developer  6441    3

现在,有了这些信息,我必须创建一些函数,例如员工的平均年龄、薪酬最高的工作、薪酬最高的员工等等。我不知道如何正确地从文件中读取数据以及如何实现这些功能。我想先定义函数,然后从文件中读取所有数据,但我的一个朋友告诉我,我可以定义每个函数,并在其中读取必要的数据。

例如,如果我要计算员工的平均年龄,我正在考虑这样做:

 def avg(*args):
        count = len(args)
        if args > 0:
            age_sum = 0
            for i in args:
                age_sum += i
            return age_sum / count
        else:
            return 0

问题是,我不知道如何为函数获取正确的数据。谁能帮我理解如何正确地做到这一点?

【问题讨论】:

  • 不幸的是,这是一个非常广泛的问题,其中似乎包含许多较小的问题。特别是在提出/回答家庭作业问题时,这将非常依赖于您在课堂上学到的内容以及您被允许/不被允许使用的内容。与其问“我该怎么做”,不如根据你的研究尝试一些事情,然后在遇到困难时用特定的minimal reproducible example 提出特定的问题
  • 我建议你从小事做起,然后从那里开始。例如,您可以弄清楚如何一次读取一行文件并打印出每一行。当你能做这么多时,你就会想出下一个小部分,你可以改变它来做其他事情。这些小步骤中的每一个最终都会构建完整的程序。

标签: python function file


【解决方案1】:

这是一种方法,但可能有比这更好的方法,但至少这将帮助您处理问题。您可以优化代码,还可以将变量从 int 更改为 float 以更好地覆盖 avg 等,并且文件中的行之间不应有空行。

#print all detail
def print_all():
  file = open("data.txt","r")
  for line in file:  
    fields = line.split(" ")
    print  ("name "+ fields[0])
    print  ("age "+ fields[1])
    print  ("occupation "+ fields[2])
    print  ("type occupation "+ fields[3])
    print  ("salary "+ fields[4])
    print  ("years_in_the_company "+ fields[5])
  file.close()
# avg salary
def avg__salary(employ = "salary" ):
  file = open("data.txt","r")
  avg=0
  for salary in file:
      salary_field = salary.split(" ")
      avg=avg+int(salary_field[4])
  file.close()
  return avg
# avg age
def avg__age(employ = "age" ):
  file = open("data.txt","r")
  avg_age=0
  for age in file:
      age_field = age.split(" ")
      avg_age=avg_age+int(age_field[1])
  file.close()
  return avg_age

# best paid job
def best_paid(employ = "paid" ):
  file = open("data.txt","r")
  bestpaid=0
  for age in file:
      age_field = age.split(" ")
      if bestpaid < age_field[4]:
         bestpaid=age_field[4]
  file.close()
  return bestpaid

number_of_lines=open('data.txt', 'r').read().count("\n") 
print("All employ detail")
print_all()
print("Avg salary is",avg__salary()/number_of_lines)
print("Avg age is",avg__age()/number_of_lines)
print("Best paid is",best_paid())

【讨论】:

  • Razvan 你可以试试这个。
猜你喜欢
  • 2019-09-18
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多