繁体   English   中英

遍历文件中的行时是否存在循环?

[英]For loop when iterating over lines in a file?

我有一个循环,如下所示:

for line in FILE:
    if ('MyExpression' in line)
        # Pull the first number out of this line and put it in a list
        # Pull the first number out of the NEXT line that has either 'MyExpression' or      'MyExpression2', and put it in a list

基本上,我想找到'My Expression exists' ,并从该行中拉出一个数字,以指示试验的开始。 然后,我想跳到包含MyExpressionMyExpression2的下一行,并从该行中提取一个数字作为我的试用的偏移量。 我想遍历整个文件,所以我有两个列表,一个表示开始,一个表示偏移。

我知道如何在Matlab中执行此操作,但是在Python中,我不确定如何告诉它在下一行中显示。 就像if(第+1行中的'MyExpresion')或(第+1行中的'MyExpression2')一样?

更新:很抱歉收到较晚的答复,但这是我的文件的样子:

1234 MyExpression Blah Blah
3452 Irrelevant Blah Blah
4675 MyExpression2 Blah Blah
5234 MyExpression Blah Blah
6666 MyExpression Blah Blah

我想要两个数组/列表:基本上是[1234,5234]和[4675,6666],它们分别对应于起始点和偏移量。 我将使用当前答案,看看是否有任何答案,谢谢!

文件对象是迭代器 ,这意味着您可以使用next推进它们:

for line in FILE:
    if ('MyExpression' in line):
        next_line = next(FILE, None)

请注意,如果None到达文件末尾,则其中的None将返回默认值。 没有它,将引发StopIteration异常。

for line in afile:循环的主体中的for line in afile: ,尚未读取下一行; 但是,您可以继续阅读所述循环体内的以下几行。 例如:

for line in afile:
    if 'MyExpression' in line:
        # ...the number extraction, e.g with a regular expression, then:
        for nextline in afile:
            if 'MyExpression' in nextline or 'MyExpression2' in nextline:
                # the other number extraction, then
                break  # done with the inner loop

请注意,这consumes afile中剩余的一部分(或全部)。 如果您需要再次遍历该部分,则需要使用itertools.tee来创建afile迭代器的两个“克隆”,然后在“克隆”上循环。 但是,据我对您的问题的了解,这对于您的特定要求不是必需的(而且有点棘手,因此我不会对此进行详细说明)。

因此,例如,如果a.txt是您提供的示例文件:

1234 MyExpression Blah Blah
3452 Irrelevant Blah Blah
4675 MyExpression2 Blah Blah
5234 MyExpression Blah Blah
6666 MyExpression Blah Blah

然后这个示例代码:

with open('a.txt') as afile:
    results = []
    for line in afile:
        if 'MyExpression' in line:
            first = int(line.split()[0])
            for nextline in afile:
                if 'MyExpression' in nextline or 'MyExpression2' in nextline:
                    second = int(nextline.split()[0])
                    results.append([first, second])
                    break  # done with the inner loop
    print(results)

发出

[[1234, 4675], [5234, 6666]]

不知道您想像的算法是什么,

[1234, 5234] and [4675, 6666]

什么逻辑上的规格会使4675在第一对中被忽略而在第二对中重新考虑? 当然,在您的Q文本中我看不到任何指定的内容,因此,请编辑该文本以使您的规格符合您的实际意图!

希望这对您有所帮助...查找“表达式”,并成对打印行。

text = "Expression"

# Get lines with text in it
with open('test.log') as log_file:
    the_lines = [line.strip() for line in log_file if text in line]

# Make pairs (0,1), (2,3), etc.
duples = [(the_lines[2*i], the_lines[2*i+1]) for i in xrange(len(the_lines)/2)]

# Show me...
for pair in duples:
    print pair

您应该使用自己的函数替换line.strip()以获得所需的号码。

注意:我不喜欢在创建二元组时使用索引,但是它比使用迭代器更简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM