1. 面向对象,文件操作与数据库操作复习题目:
文件score.dat中保存的是100名学生的姓名和Python课、高数和英语成绩。
(1)定义学生类,其中包含姓名、Python课、高数和英语成绩及总分、均分数据成员,成员函数根据需要确定。
(2)读入这名学生的成绩,用对象列表进行存储。
(3)求出各科和总分的最高分。
(4)请按总分的降序(高成绩在前,低成绩在后)排序
(5)在屏幕上显示各科及总分的最高分,排序后的成绩单(包括总分)保存到文件odered_score.dat中。
(6) 将文件中的所有学生信息, 保存在mariadb数据库中;
import random
import pymysql
from itertools import chain
def data_create():
with open('score.dat','w') as f:
first = ['赵','王','李','张']
second = ['伟','勇','富贵','杰','涛']
for i in range(100):
name = random.choice(first)+random.choice(second)
PythonScore = random.randint(0,100)
MathScore = random.randint(0,100)
EnglishScore = random.randint(0,100)
f.write(name+' '+str(PythonScore)+' '+str(MathScore)+' '+str(EnglishScore)+'\n')
class student(object):
def __init__(self,name,PythonScore,MathScore,EnglishScore):
self.name = name
self.PythonScore = float(PythonScore)
self.MathScore = float(MathScore)
self.EnglishScore = float(EnglishScore)
self.SumScore = sum([self.PythonScore,self.MathScore,self.EnglishScore])
self.AvgScore = self.SumScore/3
def __repr__(self):
return '姓名: %s python成绩: %s 数学成绩: %s 英语成绩: %s 总分: %s 平均分: %.2f'%(self.name,
self.PythonScore,self.MathScore,self.EnglishScore,self.SumScore,self.AvgScore)
def main():
data_create()
#读取学生成绩,并使用对象列表储存
with open ('score.dat') as f:
studentli=[student(*line.split()) for line in f.readlines()]
# print(studentli)
#各科最高分
print('Python最高分: %s'%max(studentli,key=lambda x:x.PythonScore).PythonScore)
print('数学最高分: %s'%max(studentli,key=lambda x:x.MathScore).MathScore)
print('英语最高分: %s'%max(studentli,key=lambda x:x.EnglishScore).EnglishScore)
SumScore_li = sorted(studentli,key=lambda x:x.SumScore,reverse=True)
print('最高分: %s'%SumScore_li[0].SumScore)
with open('odered_score.dat','w') as f:
for i in SumScore_li:
print(i)
f.write(str(i)+'\n')
#读取odered_score.dat将其写入数据库
with open('odered_score.dat') as f1:
conn = pymysql.connect(user='root',password='redhat',charset='utf8',db='student',autocommit=True)
cur = conn.cursor()
for line in f1.readlines():
getuseful = [i.split(':')for i in line.split()]
useful = list(chain(*getuseful))[2::3]#从索引值2开始步长为3
# print(useful,type(useful))
# print(useful[0],type(useful[0]))
linkuse = "insert into student values('%s','%s','%s','%s','%s','%s');"%(
useful[0],useful[1],useful[2],useful[3],useful[4],useful[5]
)#values后的%s要加'',否则会报错(这错误浪费了我40分钟)
cur.execute(linkuse)
cur.close()
conn.close()
main()