我是Python的新手,我试图找出如何从源文件中显示不同的东西。分配是编写一个程序,让用户从数学类中键入包含测试答案(A,B,C或D)的文件名,然后打开该文件,我相信我已经在下面做过了。每个文件都有不同的行数,因为每个班级的学生人数不同。每行包含学生的ID号以及他们为测试提供的答案,以逗号分隔。例如:
"N12345678,B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
该计划应该"评分"通过比较每个学生用答案键的答案来进行测试,这是
"B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
该计划还应确定并打印出文本文件中所有学生的最高分,最低分,以及分数的均值,中位数,模式和范围。
我已经编写了打开文件并计算学生人数的部分,但我一直在尝试并且未能编写将对每个学生的答案进行评分的部分。以下是我到目前为止的情况:
file_name = input("Enter a class file to grade (class1.txt, class2.txt, etc): ")
try:
outfile = open(file_name, 'r')
print("Successfuly opened",file_name)
print()
except:
print("File does not exist.")
student_counter = 0
for line in outfile:
data = (line.rstrip('\n'))
print(data)
student_counter = student_counter + 1
print(student_counter)
以下是我为评估每个学生的答案而尝试的内容,但它似乎并没有起作用。每个正确答案值4分,每个错误从总分中减去1,每个问题留空是0分:
answers = ["B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"]
total = 1
counter = 1
for line in outfile:
student_counter = student_counter + 1
text_line = line.split(',')
if (text_line[counter] == answers[counter-1]):
total = total+4
elif text_line[counter] == ' ':
total = total
counter = counter +1
else:
total = total-1
print(total)
如何编辑我的程序以迭代输入文件中的每一行并显示最高分,最低分,中位数,模式和范围?
答案 0 :(得分:2)
split(delimiter)
是你的朋友。一种可能的解决方案是迭代文件中的行,拆分它们并将它们与键进行比较。 zip
功能派上用场:如果你也分开了密钥,你最终会得到两个长度相同的列表,其中一个列表包含学生的答案,第二个列表包含正确答案。
zip
从这两个列表中创建单个元组列表,其中每个元组包含学生的答案和正确答案,您可以简单地比较这两个元素。
为了进行未来的计算,简单的方法是将结果保存到某些外部结构,然后进行计算。执行此操作的代码可能如下所示:
key = 'B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D'.split(',')
students = {}
with open('grades', 'r') as f:
for line in f:
line_split = line.rstrip('\n').split(',')
students[line_split[0]] = 0
for key, answer in zip(key, line_split[1:]):
if key == answer:
students[line_split[0]] = students[line_split[0]] + 4
else:
students[line_split[0]] = students[line_split[0]] - 1
print students
给出输出
{' N12345678':100}
表示您的示例数据。
如果你要迭代结果并进行一些计算,你可以通过
来完成for student, score in students:
print score
但是我会把计算留给你,这样你就可以自己解决这个问题了。
答案 1 :(得分:0)
如果您可以使用词典,我建议将此代码作为选项:
answers = ['B', 'A', 'D', 'D', 'C', 'B', 'D', 'A', 'C', 'C', 'D', 'B', 'A', 'B', 'A', 'C', 'B', 'D', 'A', 'C', 'A', 'A', 'B', 'D', 'D']
students = {}
# Example of a line from the outfile
outfile = ["N12345678,B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"]
# This simulates the loop used to iterate over the textfile
for line in outfile:
total = 0 # Total score for the student
student_answers = line.split(',') # The student and his answers
# We enumerate each element of the student's answer sheet. We exclude his ID for obvious reasons
for i, answer in enumerate(student_answers[1:]):
if (answer == answers[i]): #Correct answer
total += 4
elif text_line[counter] != answers[i]: # Wrong answer
total -= 1
else: # Blank answer, we pass to the next iteration
pass
# We finally asociate each student's ID to his score.
students[student_answers[0]] = total
print(students)