文件score.dat中保存的是100名学生的姓名和Python课、高数和英语成绩。
1)定义学生类,其中包含姓名、Python课、高数和英语成绩及总分、均分数据成员,成员函数根据需要确定。
2)读入这名学生的成绩,用对象列表进行存储。
3)求出各科和总分的最高分。
4)请按总分的降序(高成绩在前,低成绩在后)排序
5)在屏幕上显示各科及总分的最高分,排序后的成绩单(包括总分)保存到文件odered_score.dat中。
6) 将文件中的所有学生信息, 保存在mariadb数据库中
import random
import pymysql
from itertools import chain
#生成100名学生的成绩
def createdata():
with open('score.dat', 'w') as f:
for i in range(1,101):
name = 'student' + str(i)
python_score = random.randint(60, 100)
math_score = random.randint(60, 100)
english_score = random.randint(60, 100)
f.write(name + '\t' + str(python_score) + '\t' + str(math_score) + '\t' + str(english_score) + '\n')
#建立Student类
class student(object):
def __init__(self, name, python_score, math_score, english_score):
self.name = name
self.python_score = python_score
self.math_score = math_score
self.english_score = english_score
self.sumscore = float(python_score) + float(math_score) + float(english_score)
self.averagescore = self.sumscore / 3
def __repr__(self):
return '姓名:%s python分数:%s 高数分数:%s 英语分数:%s 总分:%s 平均分:%.2f' % (
self.name, self.python_score, self.math_score, self.english_score, self.sumscore, self.averagescore)
def main():
createdata()
#读取 score.dat 文件中的学生成绩,并使用对象列表存储
with open('score.dat') as f:
studentlist = [student(*line.split()) for line in f.readlines()]
#输出各科成绩最高分
print('python最高分:%s' % max(studentlist, key=lambda x: x.python_score).python_score)
print('高数最高分:%s' % max(studentlist, key=lambda x: x.math_score).math_score)
print('英语最高分:%s' % max(studentlist, key=lambda x: x.english_score).english_score)
#对总成绩进行排序,并输出最高分,将排序后的成绩写入文件 odered_score.dat
sumscorelist = sorted(studentlist, key=lambda x: x.sumscore, reverse=True)
print('总分最高:%s' % sumscorelist[0].sumscore)
with open('odered_score.dat', mode='w') as f:
for i in sumscorelist:
print(i)
f.write(str(i) + '\n')
#读取 odered_score.dat 文件, 并将数据写入数据库
with open('odered_score.dat') as f:
conn = pymysql.connect(host='localhost',user='root', password='redhat', charset='utf8', db='mariadb', autocommit=True)
cur = conn.cursor()
#cur.execute('drop table student;')
newcreate = 'create table student(姓名 varchar(10) not null, python成绩 varchar(5), 高数成绩 varchar(5), 英语成绩 varchar(5), 总分 varchar(5), 平均分 varchar(5));'
cur.execute(newcreate)
for line in f.readlines():
getuseful = [i.split(':') for i in line.split()]
useful = list(chain(*getuseful))[1::2]
linkuse = "insert into student values('%s', '%s', '%s', '%s', '%s', '%s');" % (
useful[0], useful[1], useful[2], useful[3], useful[4], useful[5])
#print(linkuse)
cur.execute(linkuse)
cur.close()
conn.close()
main()
写入数据库:
eg:
1.生成一个大文件ips.txt,要求120000行,每行随机为172.25.254.0/24段的ip
2.读取ips.txt文件统计这个文件中ip出现频率排前10的ip