Python如何读取文本文件整数并按规则存入Timetable与slots类结构
实现逻辑
- 先读取文件所有行,过滤空行后转换为整数序列
- 用
0作为分隔符拆分整数序列,得到每个班级对应的独立数据块 - 每个数据块的第一个元素为班级ID,剩余元素按步长3遍历,每3个值生成一个slots实例,最终组装为Timetable对象
完整实现代码
class Timetable: def __init__(self): self.id = "" self.slot = [] class slots: def __init__(self): self.day = 0 self.slot = 0 self.room = 0 def load_timetables(file_path): timetables = [] # 预处理文件为整数序列 with open(file_path, 'r', encoding='utf-8') as f: nums = [] for line in f: line = line.strip() if line: nums.append(int(line)) # 按分隔符0拆分班级数据块 blocks = [] current_block = [] for num in nums: if num == 0: if current_block: blocks.append(current_block) current_block = [] else: current_block.append(num) if current_block: blocks.append(current_block) # 组装类实例 for block in blocks: tt = Timetable() tt.id = str(block[0]) # 步长为3遍历,每3个值生成一个slot实例 for i in range(1, len(block), 3): s = slots() s.day = block[i] s.slot = block[i+1] s.room = block[i+2] tt.slot.append(s) timetables.append(tt) return timetables # 测试示例 if __name__ == "__main__": all_timetables = load_timetables("你的文件路径.txt") # 打印第一个班级的信息验证 print(f"班级ID:{all_timetables[0].id}") for slot_item in all_timetables[0].slot: print(f"周{slot_item.day} 第{slot_item.slot}时隙 {slot_item.room}号教室")
运行验证
用你提供的示例文件运行上述代码,输出如下:
班级ID:1 周2 第2时隙 9号教室 周3 第2时隙 9号教室
和预期逻辑完全一致。
内容的提问来源于stack exchange,提问作者Awais Shahid
相关产品推荐
相关产品推荐

