是否可以编写一个python程序,使您能够用python对文本文件的内容进行排序
我一直在写一个数学测验,程序向学生提问,然后保存他们的分数,如下所示:是否可以编写一个python程序,使您能够用python对文本文件的内容进行排序,python,excel,sorting,random,average,Python,Excel,Sorting,Random,Average,我一直在写一个数学测验,程序向学生提问,然后保存他们的分数,如下所示: class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number") filename = (str(class_number) + "txt") with open(filename, 'a') as f: f.write("\n" + str(name)
class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
filename = (str(class_number) + "txt")
with open(filename, 'a') as f:
f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n")
with open(filename) as f:
lines = [line for line in f if line.strip()]
lines.sort()
if prompt_bool("Do you wish to view previous results for your class"):
for line in lines:
print (line)
else:
sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
但是,我被指示将最后三个分数保存到学生姓名中,然后显示最后三个分数的平均值。这需要将分数保存到学生姓名。我正在考虑将其外包给excel,但我不知道如何使用测试文件或文本文件在excel中打开
以下是代码的其余部分:
import random
import sys
def get_input_or_quit(prompt, quit="Q"):
prompt += " (Press '{}' to exit) : ".format(quit)
val = input(prompt).strip()
if val.upper() == quit:
sys.exit("Goodbye")
return val
def prompt_bool(prompt):
while True:
val = get_input_or_quit(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
print ("Invalid input '{}', please try again".format(val))
def prompt_int_small(prompt='', choices=(1,2)):
while True:
val = get_input_or_quit(prompt)
try:
val = int(val)
if choices and val not in choices:
raise ValueError("{} is not in {}".format(val, choices))
return val
except (TypeError, ValueError) as e:
print(
"Not a valid number ({}), please try again".format(e)
)
def prompt_int_big(prompt='', choices=(1,2,3)):
while True:
val = get_input_or_quit(prompt)
try:
val = int(val)
if choices and val not in choices:
raise ValueError("{} is not in {}".format(val, choices))
return val
except (TypeError, ValueError) as e:
print(
"Not a valid number ({}), please try again".format(e)
)
role = prompt_int_small("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")
if role == 1:
score=0
name=input("What is your name?")
print ("Alright",name,"welcome to your maths quiz."
" Remember to round all answers to 5 decimal places.")
level_of_difficulty = prompt_int_big("What level of difficulty are you working at?\n"
"Press 1 for low, 2 for intermediate "
"or 3 for high\n")
if level_of_difficulty == 3:
ops = ['+', '-', '*', '/']
else:
ops = ['+', '-', '*']
for question_num in range(1, 11):
if level_of_difficulty == 1:
max_number = 10
else:
max_number = 20
number_1 = random.randrange(1, max_number)
number_2 = random.randrange(1, max_number)
operation = random.choice(ops)
maths = round(eval(str(number_1) + operation + str(number_2)),5)
print('\nQuestion number: {}'.format(question_num))
print ("The question is",number_1,operation,number_2)
answer = float(input("What is your answer: "))
if answer == maths:
print("Correct")
score = score + 1
else:
print ("Incorrect. The actual answer is",maths)
if score >5:
print("Well done you scored",score,"out of 10")
else:
print("Unfortunately you only scored",score,"out of 10. Better luck next time")
class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
filename = (str(class_number) + 'txt')
with open(filename, 'a') as f:
f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n")
with open(filename) as f:
lines = [line for line in f if line.strip()]
lines.sort()
if prompt_bool("Do you wish to view previous results for your class"):
for line in lines:
print (line)
else:
sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
首先,我将创建数据库,并使用sqlite的db browser查看它,如下图所示 注意:忽略db browser自动生成的顶部表格,您感兴趣的是其他2个表格。您将使用的方法是使用两个学生id将表链接在一起,每次添加一个学生时,学生id将自动递增,这意味着它将为您生成,并为每个新记录递增1 有了它,就有了您想要的所有sql,下面显示的是创建/清除表所需的sql:
sql = """CREATE TABLE `tbl_Students` (
`StudentID` INTEGER PRIMARY KEY AUTOINCREMENT,
`FirstName` TEXT,
`LastName` TEXT
)"""
#this is the sql that will be run
with sqlite3.connect("studentscores.db") as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",("tbl_Students",))
result = cursor.fetchall()
cursor.execute("drop table if exists {0}".format("tbl_Students")) #if table exist delete it
cursor.execute(sql)
db.commit()
#this is the sql that will be run
sql = """CREATE TABLE `tbl_scores` (
`StudentID` INTEGER,
`DateOfScore` INTEGER,
`Score` INTEGER
)"""
with sqlite3.connect("studentscores.db") as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",("tbl_scores",))
result = cursor.fetchall()
cursor.execute("drop table if exists {0}".format("tbl_scores"))#if table exist delete it
cursor.execute(sql)
db.commit()
self.cleardb.set("database cleared")
接下来是将值插入数据库
with sqlite3.connect("studentscores.db") as db:
cursor=db.cursor()
sql = "insert into tbl_Students (FirstName, Lastname) values (?,?)"
cursor.execute(sql,(firstname,lastname))
db.commit()
with sqlite3.connect("studentscores.db") as db:
cursor=db.cursor()
sql = "insert into tbl_scores (StudentID, DateOfScore, Score) values (?,?, ?)"
cursor.execute(sql,(StudentID,nDateOfScore,nScore))
db.commit()
当为分数插入值时,我会让用户先选择一个学生,这样您就可以链接两个表。我经常使用树来进行链接,但也可以使用下拉列表,通过使用数据库中的数据来填充
with sqlite3.connect("studentscores.db") as db:
cursor=db.cursor()
sql = "insert into tbl_Students (FirstName, Lastname) values (?,?)"
cursor.execute(sql,(firstname,lastname))
db.commit()
with sqlite3.connect("studentscores.db") as db:
cursor=db.cursor()
sql = "insert into tbl_scores (StudentID, DateOfScore, Score) values (?,?, ?)"
cursor.execute(sql,(StudentID,nDateOfScore,nScore))
db.commit()
第三是更新价值观
with sqlite3.connect("studentscores.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=? where StudentID=?"
cursor.execute(sql,(FirstName,LastName,StudentID))
db.commit()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "delete from tblStudents where StudentID = ?"
cursor.execute(sql,(StudentID))
db.commit()
最后是删除值
with sqlite3.connect("studentscores.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=? where StudentID=?"
cursor.execute(sql,(FirstName,LastName,StudentID))
db.commit()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "delete from tblStudents where StudentID = ?"
cursor.execute(sql,(StudentID))
db.commit()
我已经做了一个简单的例子,你可以添加新的学生和分数,并清除数据库注释,我把他们都放在一个表单上,但最好是把他们放在不同的菜单系统上,他们必须通过这个菜单系统。这包括将你的代码分成不同的类,如果使用object,则更改顶层定向编程
注:我使用面向对象编程实现了这一点
然后,为了满足您在问题中的要求,我将创建一个树状视图,用户在其中输入学生姓名,并在sql中使用该名称来获取所有学生的分数,然后将这些分数按顺序排序,取前3名并取平均值
要对这些日期进行排序,请首先将它们转换为日期时间-
然后,要对它们进行排序-请不要让我们先解析您的代码,以确定您的文件格式。此外,问题标题与您在问题中描述的任务有什么关系?此外,文件I/O是问题所在,还是创建适当的映射是问题所在?我们应该从哪里开始?TL;医生:对不起,我不知道我基本上是说你的问题不清楚,你应该阅读我给你的链接。读了这篇评论后,我仍然不明白。你能帮我吗。你不明白我有多绝望你以前用过SQL吗?您可以使用一个数据库,该数据库将存储两个表,使用主键和外键进行学生和分数链接,然后当询问最后3个分数的平均值时,获取所有学生的分数,并过滤掉最新的3个。我认为这比使用excel或txt文件要好。