赞
踩
目录
- import os.path
- import re
-
- filename = "students.txt"
-
-
- def main():
- ctrl = True # 标记是否退出系统
- while ctrl:
- menu() # 显示菜单————调用菜单方法
- option = input("请选择:")
- option_str = re.sub("\D", "", option)
- if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
- option_int = int(option_str)
- if option_int == 0:
- print("您已退出学生信息管理系统!")
- ctrl = False
- elif option_int == 1:
- insert()
- elif option_int == 2:
- search()
- elif option_int == 3:
- delete()
- elif option_int == 4:
- modify()
- elif option_int == 5:
- sort()
- elif option_int == 6:
- total()
- elif option_int == 7:
- show()
-
-
- def menu():
- print(
- "------------------------学生信息管理系统------------------------"
- "| |"
- "|==========================功能菜单============================"
- "| |"
- "| 1.录入学生信息 |"
- "| 2.查找学生信息 |"
- "| 3.删除学生信息 |"
- "| 4.修改学生信息 |"
- "| 5.排序 |"
- "| 6.统计学生总人数 |"
- "| 7.显示所有学生信息 |"
- "| 0.退出系统 |"
- "|============================================================"
- "| 说明:通过数字键上下选择菜单 |"
- "---------------------------------------------------------------"
- )
-
-
- # 将学生信息保存到文件
-
- def save(student):
- try:
- student_txt = open(filename, "a")
- except Exception as e:
- student_txt = open(filename, "w")
- for info in student:
- student_txt.write(str(info) + "\n")
- student_txt.close()
-
-
- # 实现学生信息录入功能
- def insert():
- stdentList = []
- mark = True
- while mark:
- id = input("请输入ID(如 1001):")
- if not id:
- break
- name = input("请输入名字:")
- if not name:
- break
- try:
- english = int(input("请输入英语成绩:"))
- python = int(input("请输入Python成绩:"))
- c = int(input("请输入c语言成绩:"))
- except:
- print("输入无效,不是整数值....重新录入信息")
- continue
- stdent = {"id": id, "name": name, "english": english, "python": python, "c": c}
- stdentList.append(stdent)
- inputMark = input("是否继续添加?(y/n):")
- if inputMark == "y":
- mark = True
- else:
- mark = False
- save(stdentList)
- print("学生信息录入完毕!!!")
-
-
- # 删除学生信息
- def delete():
- mark = True
- while mark:
- studentId = input("请输入要删除的学生ID: ")
- if (studentId != ""):
- if os.path.exists(filename):
- with open(filename, 'r') as rfile:
- student_old = rfile.readlines()
- else:
- student_old = []
- ifdel = False
- if student_old:
- with open(filename, 'w') as wfile:
- d = {}
- for list in student_old:
- d = dict(eval(list))
- if d['id'] != studentId:
- wfile.write(str(d) + "\n")
- else:
- ifdel = True
- if ifdel:
- print("ID为 %s 的学生信息已经被删除..." % studentId)
- else:
- print("没有找到ID为 %s 的学生信息..." % studentId)
- else:
- print("无学生信息...")
- break
- show()
- inputMark = input("是否继续删除? (y/n):")
- if inputMark == "y":
- mark = True
- else:
- mark = False
-
-
- # 修改学生信息
- def modify():
- show()
- if os.path.exists(filename):
- with open(filename, 'r') as rfile:
- student_old = rfile.readlines()
- else:
- return
- studentid = input("请输入要修改的学生ID: ")
- with open(filename, 'w') as wfile:
- for student in student_old:
- d = dict(eval(student))
- if d["id"] == studentid:
- print("找到了这名学生,可以修改他的信息!")
- while True:
- try:
- d["name"] = input("请输入姓名: ")
- d["english"] = int(input("请输入英语成绩: "))
- d["python"] = int(input("请输入Python成绩: "))
- d["c"] = int(input("请输入C语言成绩: "))
- except:
- print("您的输入有误,请重新输入。")
- else:
- break
- student = str(d)
- wfile.write(student + "\n")
- print("修改成功! ")
- else:
- wfile.write(student)
- mark = input("是否继续修改其他学生信息? (y/n):")
- if mark == "y":
- modify()
-
-
- # 查询学生信息
- def search():
- mark = True
- student_query = []
- while mark:
- id = ""
- name = ""
- if os.path.exists(filename):
- mode = input("按ID查输入1;按姓名查输入2: ")
- if mode == "1":
- id = input("请输入学生ID: ")
- elif mode == "2":
- name = input("请输入学生姓名: ")
- else:
- print("您的输入有误,请重新输入!")
- search()
- with open(filename, 'r') as file:
- student = file.readlines()
- for list in student:
- d = dict(eval(list))
- if (id != ""):
- if d['id'] == id:
- student_query.append(d)
- elif (name != ""):
- if d['name'] == name:
- student_query.append(d)
- show_student(student_query)
- student_query.clear()
- inputMark = input("是否继续查询?(y/n):")
- if inputMark == "y":
- mark = True
- else:
- mark = False
- else:
- print("暂未保存数据信息...")
- return
-
-
- # 统计学生总人数
- def total():
- if os.path.exists(filename):
- with open(filename, "r") as rfile:
- student_old = rfile.readlines()
- if student_old:
- print("一共有%d名学生!" % len(student_old))
- else:
- print("还没录入学生信息!")
- else:
- print("暂未保存数据信息。。。")
-
-
- # 显示所有学生信息
- def show():
- student_new = []
- if os.path.exists(filename):
- with open(filename, "r") as rfile:
- student_old = rfile.readlines()
- for list in student_old:
- student_new.append(eval(list))
- if student_new:
- show_student(student_new)
-
-
- def show_student(studentList):
- if not studentList:
- print("(o@.@o) 无数据信息 (o@.@o) \n")
- return
- # 定义标题显示格式
- format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^10}"
- print(format_title.format("ID", "名字", "英语成绩", "Python成绩", "C语言成绩", "总成绩"))
- # 定义具体内容显示格式
- format_data = "{:^6}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
- for info in studentList:
- print(format_data.format(info.get("id"),
- info.get("name"), str(info.get("english")), str(info.get("python")),
- str(info.get("c")),
- str(info.get("english") + info.get("python") +
- info.get("c")).center(12)))
-
-
- # 排序
- def sort():
- show()
- if os.path.exists(filename):
- with open(filename, "r") as file:
- student_old = file.readlines()
- student_new = []
- for list in student_old:
- d = dict(eval(list))
- student_new.append(d)
- else:
- return
- ascORdesc = input("请选择(0升序;1降序):")
- if ascORdesc == "0":
- ascORdescBool = False
- elif ascORdesc == "1":
- ascORdescBool = True
- else:
- print("你的输入有误,请重新输入")
- sort()
- mode = input("请选择排序方法(1按英语成绩排序;2按python成绩排序;3按c语言成绩排序;0按总成绩排序)")
- if mode == "1":
- student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)
- elif mode == "2":
- student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool)
- elif mode == "3":
- student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool)
- elif mode == "0":
- student_new.sort(key=lambda x: x["english"] + x["python"] + x["python"], reverse=ascORdescBool)
- else:
- print("您输入有误,请重新输入!")
- sort()
- show_student(student_new)
-
-
- if __name__ == '__main__':
- main()
- # @Project : 学生信息管理系统
- # @Author : 黄前程
- # @Time : 2023/10/17 21:00
- # 请尊重作者的劳动成果,转载请注明出处
- # -----------------------------------------------
-
- class Student:
- def __init__(self, id, name, age, english, python, c):
- self.id = id
- self.name = name
- self.age = age
- self.english = english
- self.python = python
- self.c = c
-
- # __str__方法用于返回对象的描述信息,如果不使用__str__方法,直接print,或者return,返回的是对象的内存地址。
- # 如果在__str__中定义了描述信息,print或者return时,返回的就不是内存地址,显示更友好,实现了类到字符串的转化。
- def __str__(self):
- return (f"ID: {self.id:<6} | Name: {self.name:<10} | Age: {self.age:<6} "
- f"| English: {self.english:<6} | Python: {self.python:<6} | C: {self.c:<6}")
-
-
- class StudentManager:
- def __init__(self, file_name):
- self.students = []
- self.file_name = file_name
- try:
- with open(file_name, "r") as file:
- for line in file:
- student_info = line.strip().split(",")
- student = Student(student_info[0], student_info[1], int(student_info[2]), float(student_info[3]),
- float(student_info[4]), float(student_info[5]))
- self.students.append(student)
- except FileNotFoundError:
- print("系统中没有学生信息,请先录入学生信息!")
-
- def save_to_file(self):
- with open(self.file_name, "w") as file:
- for student in self.students:
- file.write(
- f"{student.id},{student.name},{student.age},{student.english},{student.python},{student.c}\n")
-
- def add_student(self, student):
- self.students.append(student)
- self.save_to_file()
-
- def delete_student(self, id):
- self.students = [student for student in self.students if student.id != id]
- self.save_to_file()
-
- def update_student(self, id, new_info):
- for student in self.students:
- if student.id == id:
- student.name = new_info[0]
- student.age = int(new_info[1])
- student.english = float(new_info[2])
- student.python = float(new_info[3])
- student.c = float(new_info[4])
- self.save_to_file()
- break
-
- def sort_students(self):
- self.students.sort(key=lambda student: student.english + student.python + student.c, reverse=True)
-
- def count_students(self):
- return len(self.students)
-
- def show_all_students(self):
- for student in self.students:
- print(student)
-
- def show_student(self, id):
- for student in self.students:
- if student.id == id:
- print(student)
- break
-
-
- def main():
- manager = StudentManager("students.txt")
- while True:
- print('''
- ------------------------学生信息管理系统------------------------
- | |
- |==========================功能菜单===========================|
- | |
- | 1.录入学生信息 |
- | 2.查找学生信息 |
- | 3.删除学生信息 |
- | 4.修改学生信息 |
- | 5.排序(成绩从高到低) |
- | 6.统计学生总人数 |
- | 7.显示所有学生信息 |
- | 0.退出系统 |
- |============================================================|
- | |
- ---------------------------------------------------------------
- '''
- )
- option = input("请选择:")
- if option == "1":
- while True:
- try:
- id = input("请输入学生ID: ")
- name = input("请输入学生姓名: ")
- age = int(input("请输入学生年龄: "))
- english = float(input("请输入英语成绩: "))
- python = float(input("请输入Python成绩: "))
- c = float(input("请输入C语言成绩: "))
- except:
- print("您的输入有误,请重新输入。")
- else:
- break
- manager.add_student(Student(id, name, age, english, python, c))
- elif option == "2":
- id = input("请输入要查询的学生ID: ")
- if id in [student.id for student in manager.students]:
- print(f"学生在系统中")
- manager.show_student(id)
- else:
- print(f"没有找到ID: {id}的学生")
- elif option == "3":
- id = input("请输入要删除的学生ID: ")
- manager.delete_student(id)
- elif option == "4":
- while True:
- id = input("请输入要更新信息的学生ID: ")
- try:
- new_info = input("请输入完整的新信息,格式:姓名 年龄 英语成绩 python成绩 c语言成绩:\n").split(" ")
- manager.update_student(id, new_info)
- except:
- print("您的输入有误,请重新输入。")
- else:
- break
- elif option == "5":
- manager.sort_students()
- elif option == "6":
- count = manager.count_students()
- print(f"学生总数:{count}")
- elif option == "7":
- manager.show_all_students()
- elif option == "0":
- print("Exiting the system...")
- break
- else:
- print("请输入正确的选项!")
-
-
- if __name__ == '__main__':
- main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。