gpt4 book ai didi

python - 遍历文件中的行时进行循环?

转载 作者:太空宇宙 更新时间:2023-11-04 07:19:02 24 4
gpt4 key购买 nike

我有一个循环如下:

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 ('MyExpression' in line+1) OR ('MyExpression2' in line+1)?

更新:很抱歉回复晚了,但我的文件可能是这样的:

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

我想要两个数组/列表:基本上是 [1234, 5234] 和 [4675, 6666],它们对应于开始和偏移。我会尝试使用当前的答案,看看是否有人这样做,谢谢!

最佳答案

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

请注意,此消耗 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 文本中我看不到任何具体说明,因此,请编辑该文本以使您的规范符合您的实际意图!

关于python - 遍历文件中的行时进行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com