假设名为“File1.txt”的文本文件具有以下结构:
random information
data #29, 45392 records
Unit: Unit1 Location: AA11
2011-09-20 14:06:20.78 28 finished
more random info
2017-04-19 09:11:59.00 00:01:02.30 A24 8 7
2017-04-19 09:12:02.25 00:00:01.00 A22 3 3
我们希望从该数据中收集单元的名称(在本例中为Unit1
,如文件第3行所示),以便引用其值并将其存储在数据帧中。我们可以通过以下代码实现这一点:
un = [] #to store unit name
with open("File1.txt","r") as fi:
for line in fi:
if line.startswith("Unit"):
un.append(line.split()[1])
# we could then create a dataframe and populate it with the value of un as needed
现在,如果文本文件(来自同一“单元”)有多行以Unit
开头,该怎么办
random information
data #29, 45392 records
Unit: Unit1 Location: AA11
2011-09-20 14:06:20.78 28 finished
more random info
2017-04-19 09:11:59.00 00:01:02.30 A24 8 7
2017-04-19 09:12:02.25 00:00:01.00 A22 3 3
Unit: Unit1 Location: AA11
以Unit
开头的两行都包含相同的信息(即我们单元的名称:Unit1
),因此我们只需要收集一次名称。在这种情况下,使用上面的脚本将产生一个包含两个元素的列表(Unit1
将重复两次)。当循环的计算结果为真时,我们如何从本质上告诉它停止
使用break
相关问题 更多 >
编程相关推荐