博客
关于我
Python-类与文件读取结合
阅读量:796 次
发布时间: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和RF编写接口自动化
    查看>>
    python和js哪个难_【Python】记一次学习,Python 与 js 在实现闭包时的差异
    查看>>
    python和java哪个更值得学——来自知乎高赞回答
    查看>>
    python和c混合编程 github_在pycharm中使用git版本管理以及同步github的方法
    查看>>
    python命名空间更改_Python模块xml.etree.ElementTree自动修改xml命名空间键
    查看>>
    Python命名中尾随下划线有什么好处?
    查看>>
    Python启动脚本
    查看>>
    Python听写汇总结果
    查看>>
    python吊打Excel?屁!那是你不会用!
    查看>>
    Python合并两张图片 | 先叠透明度再合并 (附Demo)
    查看>>
    python各进制的表述与转换
    查看>>
    python各种库安装
    查看>>
    python可视化matplotlib_如何使用Python中最强大的可视化工具Matplotlib?
    查看>>
    python可维护性_使用这7大神器,让你的Python 代码更容易于维护
    查看>>
    Python只运行一次while循环
    查看>>
    python变量的详细教程_Python零基础入门教程之语法入门[变量](第二期)
    查看>>
    Python变量命名方法-ChatGPT4o作答
    查看>>
    Python变量与运算符
    查看>>
    Python变量/运算符/函数/模块/string
    查看>>
    python发送邮件的时候出现 error (535, b‘5.7.3 Authentication unsuccessful‘) 解决方法
    查看>>