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

效果示例:

在這裏插入圖片描述

代碼示例:

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()

如有不足,請留言告知!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章