使用Python2.4时,我正在读取一个大的平面文件并选择一个特定的行号。现在我想搜索一个字符串,比如说,在行号之前的START,和在行号之后的字符串END。
如何获取字符串START (当前行号之前)和END (当前行号之后)的最近匹配项的行号?
发布于 2011-05-30 19:07:33
这样如何:
line_no = 1
# Seek the last START before reaching the target line.
start_line_no = -1
while line_no != target_line_no:
line = input.readline()
if line == "":
# File is shorter than you think.
break
line_no += 1
if START in line:
start_line_no = line_no
# Seek the first END after the target line.
end_line_no = -1
while true:
line = input.readline()
if line == "":
# END could not be found.
break
line_no += 1
if END in line:
end_line_no = line_no
break
print start_line_no, end_line_nohttps://stackoverflow.com/questions/6175091
复制相似问题