从两个方向的行号中搜索字符串

时间:2011-05-30 10:25:08

标签: python string search variables

使用Python 2.4,我正在阅读一个大型平面文件并选择一个特定的行号。现在,我想在该行号之前搜索字符串,例如START,并在该行号后搜索字符串END

如何获取最近出现的字符串START(当前行号前)和END(当前行号后)的行号?

1 个答案:

答案 0 :(得分:2)

这个怎么样:

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_no