줄에 키워드가 있고 그 다음 3 줄에서 다른 키워드가 발견되면 텍스트 파일을 검색하여 줄과 그 다음 3 줄을 인쇄하고 싶습니다.파이썬에서 텍스트의 검색된 부분을 이미 인쇄 한 후에 어떻게 텍스트의 후속 부분으로 이동할 수 있습니까?
지금 제 코드가 너무 많은 정보를 인쇄합니다. 한 부분이 이미 인쇄되면 다음 텍스트 섹션으로 넘어갈 수있는 방법이 있습니까?
text = """
here is some text 1
I want to print out this line and the following 3 lines only once keyword 2
print this line since it has a keyword2 3
print this line keyword 4
print this line 5
I don't want to print this line but I want to start looking for more text starting at this line 6
Don't print this line 7
Not this line either 8
I want to print out this line again and the following 3 lines only once keyword 9
please print this line keyword 10
please print this line it has the keyword2 11
please print this line 12
Don't print this line 13
Start again searching here 14
etc.
"""
text2 = open("tmp.txt","w")
text2.write(text)
text2.close()
searchlines = open("tmp.txt").readlines()
data = []
for m, line in enumerate(searchlines):
line = line.lower()
if "keyword" in line and any("keyword2" in l.lower() for l in searchlines[m:m+4]):
for line2 in searchlines[m:m+4]:
data.append(line2)
print ''.join(data)
출력은 바로 지금이다 :
이I want to print out this line and the following 3 lines only once keyword 2
print this line since it has a keyword2 3
print this line keyword 4
print this line 5
print this line since it has a keyword2 3
print this line keyword 4
print this line 5
I don't want to print this line but I want to start looking for more text starting at this line 6
I want to print out this line again and the following 3 lines only once keyword 9
please print this line keyword 10
please print this line it has the keyword2 11
please print this line 12
please print this line keyword 10
please print this line it has the keyword2 11
please print this line 12
Don't print this line 13
please print this line it has the keyword2 11
please print this line 12
Don't print this line 13
Start again searching here 14
내가 인쇄하기를 원하는 경우 :
I want to print out this line and the following 3 lines only once keyword 2
print this line since it has a keyword2 3
print this line keyword 4
print this line 5
I want to print out this line again and the following 3 lines only once keyword 9
please print this line keyword 10
please print this line it has the keyword2 11
please print this line 12
입니다 두 번째 검색어와 일치하는 – MattH