2018河南科技学院--Python面向对象课程设计

2018河南科技学院–Python面向对象课程设计

题目要求:

记事本inform.txt中存放若干学生的相关信息,请按照要求编写对应的类(student),将信息从文件中读取出来,要求使用列表存储学生信息,并按照学生分数情况绘制柱状图。

记事本inform.txt内容示例如下(也可以自行编写):

姓名 年龄 性别 分数
程玲玲 21 女 87
李丽 19 女 77
曹俊 21 男 50
何晓磊 12 男 78
李丽 20 女 97
程玲 23 女 67

注意:

python:python3.6.4

工具:JetBrains PyCharm 2018.2.3 x64

需要安装两个模块:pip install matplotlib

​ pip install numpy

需要创建文件:inform.txt

需要在inform.txt的文件存放:

姓名 年龄 性别 分数
程玲玲 21 女 87
李丽 19 女 77
曹俊 21 男 50
何晓磊 12 男 78
李丽 20 女 97
程玲 23 女 67

效果示例:

2018河南科技学院--Python面向对象课程设计

代码示例:

import numpy as np
import matplotlib.pyplot as plt


class Student(object):
    """学生类"""

    def __init__(self, name, age, sex, score):
        """
        初始化学生属性
        :param name: 姓名
        :param age: 年龄
        :param sex: 性别
        :param score: 分数
        """
        self.name = name
        self.age = age
        self.sex = sex
        self.score = score


class ShowStudentInformation(object):
    """展示学生信息"""

    def __init__(self, inform_path):
        self.path = inform_path

    def parse_file(self):
        """解析文件, 输出存储学生对象的列表"""
        with open(self.path, encoding='utf-8') as fp:
            inform_list = [i.strip() for info in fp.readlines() for i in info.split(' ') if i]
        student_count = int(len(inform_list[4:]) / 4)
        student_inform = []
        for i in np.arange(student_count):
            student_inform.append(Student(
                inform_list[4:][i*4],
                inform_list[4:][i*4+1],
                inform_list[4:][i*4+2],
                int(inform_list[4:][i*4+3])
            ))
        return student_inform

    def show_score(self, student_inform):
        """展示学生分数"""
        plt.figure(figsize=(8, 6), dpi=80)
        plt.subplot(1, 1, 1)
        name_list = [student.name for student in student_inform]
        score_list = [student.score for student in student_inform]
        index = np.arange(len(name_list))
        plt.bar(index, score_list, label="Score")
        plt.xlabel('Student Name')
        plt.ylabel('Student Score')
        plt.title('Show Student Score')
        plt.xticks(index, name_list)
        plt.yticks(np.arange(0, 101, 10))
        plt.legend(loc="upper right")
        plt.show()

    def main(self):
        self.show_score(self.parse_file())


if __name__ == '__main__':
    ssi = ShowStudentInformation('inform.txt')
    ssi.main()

如有不足,请留言告知!