gpt4 book ai didi

python - 使用 python next() 和 strip() 检索以下行

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

我在使用 next()strip() 检索我正在阅读的行之后的行时遇到问题。测试数据看起来像这样:

@abcde:111/2
ABCDEFGHIj
+abcde:111/2
bla11
@abcde:115/2
JDIJSKNDIJ
+abcde:115/2
bla13
@abcde:113/2
djijwkoken
+abcde:113/2
bla15

我的目标是删除所有以“@”开头且第二行包含“N”的 4 行。预期的测试输出应如下所示:

@abcde:111/2
ABCDEFGHIj
+abcde:111/2
bla11
@abcde:113/2
djijwkoken
+abcde:113/2
bla15

这是我的代码 (delete_N.py),我在远程 Ubuntu 服务器上使用 Mac OS 终端运行它,使用 python 2.7:

import sys

filename1 = sys.argv[1] #file to process

data = open(filename1, 'r')

def del_N(input1):
for line in input1:
if line[:1] == '@' and 'N' not in next(input1).strip():
print line.strip()
for i in range(3):
print next(input1).strip()

del_N(data)

但是我得到以下错误:

Traceback (most recent call last):
File "delete_N.py", line 14, in <module>
del_N(data)
File "delete_N.py", line 12, in del_N
print next(input1).strip()
StopIteration

我做错了什么?

最佳答案

在您的程序中,您正在从文件中读取数据。检查Lego's answer ,他非常清楚地解释了错误。

你可以这样做。该程序假定文件中的行数是 4 的倍数。

with open("Input.txt", "r") as input_file:
for line1 in input_file:
line2, line3, line4 = [next(input_file) for _ in xrange(3)]
if "N" not in line2:
print line1 + line2 + line3 + line4.rstrip()

输出

@abcde:111/2
ABCDEFGHIj
+abcde:111/2
bla11
@abcde:113/2
djijwkoken
+abcde:113/2
bla15

关于python - 使用 python next() 和 strip() 检索以下行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128364/

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