[英]How to read integer values from a text file in python (digit by digit)
我有一个这种格式的文本文件,
0
1
2 2 9
3 2 9
0
2
2 1 9
3 1 9
0
3
2 5 -6
4 1 -6
0
4
2 1 13
4 2 6
我有两个 Python 类,如下所示,
class Timetable:
def __init__(self):
self.id = ""
self.slot = []
class slots:
def __init__(self):
self.day = 0
self.slot = 0
self.room = 0
在我的文本文件中, 0充当分隔符值,即将不同的数据彼此分开。
1
2 2 9
3 2 9
其中1代表class的“ID”,后面两个是class在时间表中的slot。 如果是“2 2 9”,则表示 Class“1”的第一堂课将在“星期二,第 2 时段,9 号房间”举行
我想将所有这些数据存储在我的课程中。
例如,在本例中,我想要一个时间表 object,其中 ID 为“1”。
插槽将是两个“插槽”对象的数组。 每个时段都有一天(在本例中为 2)、时段(在本例中为 2)和房间(在本例中为 9)。
我能够读取数据,但无法区分不同的数据。 我可以使用“0”作为分隔符来区分两个类,但我现在无法区分这两个插槽。
在 C++ 中,这将非常简单,即我可以轻松地对其进行硬编码,以便将第一位数字读取为 class 的 ID。接下来的三位数字将创建插槽的第一个 object,接下来的三个数字将创建插槽的第二个 object ,依此类推,直到读取完所有文件。
但是,我无法在 Python 中做出相同的逻辑。任何人都可以帮助我这样做吗? 谢谢。
您可以像在 C++ 中那样在 python 中进行硬编码。这样 -
# Let f be file
# Assuming you know how to separate using seperator 0
# reads id. eg. id = 1
id = int(f.readline().strip())
# t1 stores list of int values. eg. t1 = [2, 2, 9]
t1 = list(map(int, f.readline().strip().split()))
# t2 stores list of int values. eg. t1 = [3, 2, 9]
t2 = list(map(int, f.readline().strip().split()))
见下文
class Timetable:
def __init__(self,id,slots):
self.id = id
self.slots = slots
def __repr__(self) -> str:
return f'Timetable: {self.id} {self.slots}'
class Slot:
def __init__(self,day,slot,room):
self.day = day
self.slot = slot
self.room = room
def __repr__(self) -> str:
return f' Slot: {self.day} {self.slot} {self.room}'
data = []
inside_tt = False
with open('data.txt') as f:
lst = []
for line in f:
line = line.strip()
if line == '0':
if not inside_tt:
inside_tt = True
else:
data.append(Timetable(id,lst))
lst =[]
next_is_id = True
continue
if inside_tt:
if next_is_id:
id = line
next_is_id = False
else:
tmp = line.split()
lst.append(Slot(tmp[0],tmp[1],tmp[2]))
data.append(Timetable(id,lst))
print(f'data: {data}')
output
data: [Timetable: 1 [ Slot: 2 2 9, Slot: 3 2 9], Timetable: 2 [ Slot: 2 1 9, Slot: 3 1 9], Timetable: 3 [ Slot: 2 5 -6, Slot: 4 1 -6], Timetable: 4 [ Slot: 2 1 13, Slot: 4 2 6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.