博客
关于我
Python-类与文件读取结合
阅读量:797 次
发布时间:2023-03-08

本文共 1614 字,大约阅读时间需要 5 分钟。


定义一个名为Student的类,包含以下属性和方法:

  • 属性:

    • name:学生姓名
    • dob:生日
    • age:年龄
    • gender:性别
    • score:分数列表
  • 方法:

    • __init__:初始化方法,接收并赋值name、dob、age、gender和score。
    • sanitize:清洗分数方法,将负数转换为正数。
    • top3:返回最大的三个分数。
    • print_stu:打印学生信息,包括最高三个分数。

  • 读取并解析txt文件:

    • 遍历工作路径下的所有txt文件。
    • 对每个文件,读取内容并解析为所需的字段。
    • 创建Student对象并添加到stu_list列表中。

    输出学生信息:

    • 遍历stu_list,调用每个学生的print_stu方法,输出姓名、生日、年龄、性别和最高三个分数。

    以下是优化后的Python代码:

    import osclass Student:    def __init__(self, name, dob, age, gender, score):        self.name = name        self.dob = dob        self.age = age        self.gender = gender        self.score = score    def sanitize(self):        self.score = [int(i) for i in self.score]        for i in range(len(self.score)):            if self.score[i] < 0:                self.score[i] = abs(self.score[i])    def top3(self):        self.sanitize()        self.score = sorted(self.score)        self.score = self.score[-3:]    def print_stu(self):        self.top3()        print(f"姓名:{self.name},生日:{self.dob},年龄:{self.age},性别:{self.gender},最高分数:{self.score}")# 读取文件并创建学生对象列表path = './aistudio/work'file_list = []for filename in os.listdir(path):    if filename.endswith('.txt'):        file_list.append(filename)stu_list = []for filename in file_list:    with open(os.path.join(path, filename), 'r', encoding='UTF-8') as f:        data = f.read().split(',')        stu = Student(            name=data[0],            dob=data[1],            age=data[2],            gender=data[3],            score=dict(map(float, data[4:]))        )        stu_list.append(stu)# 输出所有学生信息for stu in stu_list:    stu.print_stu()

    该代码定义了Student类,能够读取并解析txt文件中的数据,处理负数分数,并输出学生的信息。代码结构清晰,易于理解和维护。

    转载地址:http://rzlfk.baihongyu.com/

    你可能感兴趣的文章
    python----线程、进程、协程的区别及多线程详解
    查看>>
    python---5
    查看>>
    python---使用celery分布式系统异步发送短信(云通讯)来验证登录
    查看>>
    python--003--百分号字符串拼接、format
    查看>>
    Python--10、线程
    查看>>
    Python--Redis实战:第四章:数据安全与性能保障:第4节:复制
    查看>>
    python--基本代码规范
    查看>>
    Python--抽象类接口类
    查看>>
    PYTHON--欧拉习题二
    查看>>
    python--高级应用总结
    查看>>
    python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
    查看>>
    Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
    查看>>
    Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
    查看>>
    Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
    查看>>
    python出现 unknown encoding: idna 的处理方法
    查看>>
    Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
    查看>>
    Python-numpy(2)数组的操作
    查看>>
    Python-Numpy的tile函数用法
    查看>>
    python-open函数
    查看>>
    Python-Pandas-将特定函数应用于给定级别-多索引数据框架
    查看>>