在循环的计算结果为true时停止循环

2024-09-29 23:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

假设名为“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将重复两次)。当循环的计算结果为真时,我们如何从本质上告诉它停止


Tags: txt名称datainformationlineunitlocationrandom

热门问题