下面的简单文件操作程序是否有较短的代码



以下是问题所在,我已经编写了代码。有人能缩短答案代码吗?

假设studentdata.txt文件包含学生在各种课程中获得的成绩信息任务。每一行都有一个学生的姓氏(你可以假设是一个单词(学生获得的数字分数。所有成绩均为满分100分。学生可以出现在文件中多次。这是一个示例文件:

Arnold 90
Brown 84
Arnold 80
Cocher 77
Cocher 100

编写一个函数,将文件中的数据读入字典。然后继续提示学生姓名的用户。对于每个学生,它应该打印该学生成绩的平均值。当用户输入字典中没有的学生姓名时,停止提示。给定文件的示例运行:

Enter name: Arnold
The average for Arnold is: 85.0 
Enter name: Brown
The average for Brown is: 84.0
Enter name: Cocher
The average for Cocher is: 88.5
Enter name: Doherty
Goodbye!

这是我的代码:

import os
PATH="C:/Users/user/Desktop/studentdata.txt"
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
d=fd.read()
p1=r"b[A-za-z]+b"
p2=r"b[0-9]+b"
l1=re.findall(p1,d) 
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
l2=re.findall(p2,d)
d={}
for key,val in list(zip(l1,l2)):
if key not in d:
d[str(key)]=int(val)
else:
d[str(key)]+=int(val)
for key in d:
d[key]=d[key]/l1.count(key)

while True:
key=input("Enter name:")
if key not in d:
print("Goodbye!")
break
print("the average for "+key+" is: "+str(d[key]))
PATH = "C:/Users/user/Desktop/"
FILE = "studentdata.txt"
with open(PATH + FILE, 'r') as fp:
lines = fp.readlines()
notes_with_students = {}
for line in lines:
student = line.split()[0]
note = line.split()[1]
if student not in notes_with_students:
notes_with_students.setdefault(student, [int(note), 1])
else:
notes_with_students[student][0] += int(note)
notes_with_students[student][1] += 1
while True:
student = input("Enter name: ")
if student not in notes_with_students:
print("Goodbye!")
break
print("The average for {} is: {}".format(student, notes_with_students[student][0]/notes_with_students[student][1]))

这可能很有用。

相关内容

最新更新