You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取制表符分隔的动物体重文件并生成对应对象实例?

实现方案

1 现有代码问题修复

你现有代码存在两个可优化点:

  • 变量名不匹配:上下文管理器中定义的文件对象为file,后续调用fil.readlines()会触发NameError
  • 固定步长stepsBetweenName = 68的逻辑兼容性差,若不同动物的体重记录条数不一致会完全失效,更推荐用动态识别动物名称行的逻辑实现

2 完整实现代码

2.1 定义动物类

首先自定义动物类存储对应数据,可根据实际需求调整属性结构:

class Animal:
    def __init__(self, name):
        self.name = name
        # 存储格式为(日期, 体重)的元组,也可以改为字典以日期为键方便查询
        self.weight_records = []

    def __repr__(self):
        # 自定义打印格式,方便调试查看
        return f"Animal(name='{self.name}', record_count={len(self.weight_records)})"

2.2 数据解析逻辑

用动态识别动物名称行的逻辑解析数据,不需要固定步长,适配性更强:

animal_list = []
current_animal = None

with open(filnamn, encoding="utf-8") as file:
    lines = file.readlines()
    # 去除每行末尾空白符,同时过滤掉空行
    lines = [line.rstrip() for line in lines if line.rstrip()]

for line in lines:
    if '\t' not in line:
        # 不含制表符的行判定为动物名称行,新建实例
        current_animal = Animal(line.strip())
        animal_list.append(current_animal)
    else:
        # 拆分数据行,将日期和体重存入当前动物的记录中
        date, weight_str = line.split('\t')
        weight = float(weight_str.strip())
        current_animal.weight_records.append((date.strip(), weight))

如果你确认所有动物的记录数固定、每68行对应一个动物,也可以兼容你原有固定步长的逻辑:

animal_list = []
stepsBetweenName = 68
numberOfAnimals = int(len(lines)/stepsBetweenName)

for i in range(numberOfAnimals):
    # 截取当前动物对应的所有行
    animal_block = lines[i*stepsBetweenName : (i+1)*stepsBetweenName]
    animal = Animal(animal_block[0].strip())
    # 处理后续数据行
    for data_line in animal_block[1:]:
        date, weight_str = data_line.split('\t')
        animal.weight_records.append((date.strip(), float(weight_str.strip())))
    animal_list.append(animal)

3 效果验证

可通过以下代码查看解析结果:

for animal in animal_list:
    print(f"动物名称:{animal.name}")
    print(f"总记录条数:{len(animal.weight_records)}")
    # 打印前3条记录示例
    for date, weight in animal.weight_records[:3]:
        print(f"{date}: {weight}kg")
    print("---")

额外优化提示

  • 如果数据行的分隔符不是严格的单个制表符,可用split()替代split('\t'),会自动识别任意数量的空格/制表符作为分隔符,适配性更好。

内容的提问来源于stack exchange,提问作者dacritical

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:15:02