0

嗨,我想读取并显示 strB 的行号,这是一个常见的字符串,并在通过字符串 A 的行号读取字符串 A 后立即在文件中跟随

i am a common line
i am a common line
i am a common line
i am a common line
defghijklt 
I am a unique line 
jaslkdjaldjsadsajdlakjdasldj
spjpsijgpigjpijgjfdpgfdpgjdppdfjgdpfpi
jspijdfpgfdjgfdijgdfpjgdfpijgdfijfdoifdjpi
jgdfjfdpijfdpijgdgdjfdfjgidjgfdoijdfojgdfoijfdoo
jgdfoijfdijfdoifdjgfdoijgfdoijfdojfdoijfdojfdoifjdogfdjoi
i am a common line    
i am a common line
ueowueoodsjpdogfdpofdpofdpdfigdpgdifgdifdiikpkpjfdspjf 

这是我的代码:

strB = 'i am common line'
strA = 'I am a unique line'

input_file = open('mynewfile.txt', 'r')
with input_file as myFile:
    for num, line in enumerate(myFile):
        if strA in line:
            print num
            for num in range (num, num+12):
                if strB in line:
                    print num

请建议我该怎么办?

4

1 回答 1

1

只需设置一个标志:

input_file = open('mynewfile.txt', 'r')
with input_file as myFile:
    foundA = False
    for num, line in enumerate(myFile):
        if strA in line:
            foundA = True
            print num

        # Only look for `strB` if `strA` has been seen first
        if foundA and strB in line:
            print num
            break  # stop reading the file.

或者,嵌套循环以搜索每个 strB-after-strA事件:

input_file = open('mynewfile.txt', 'r')
with input_file as myFile:
    enumerated = enumerate(myFile):
    for num, line in enumerated:
        if strA in line:
            print num
            for num, line in enumerated:
                if strB in line:
                    print num
                    break  # search for next strA
于 2013-07-27T12:41:33.987 回答