1 #-*-coding:utf-8-*-2 __author__='Administrator'3 4 fromCollectionsImportdeque5 6 defSearch (lines, pattern, history=5):7Previons_line = Deque (maxlen=History )8 forLineinchlines:9 ifPatterninchLine :Ten yieldLine , Previons_line One Previons_line.append (line) A - - #Example use on a file the if __name__=='__main__': -With open ('. \somefile.txt') as F: - forLine, PrevlinesinchSearch (F,'python', 5): - forPlineinchPrevlines: + Print(pline) - Print(Line,"end= "") + Print('-'*20) A at
View Code
Contents of the Somefile.txt file:
The first call to the search () function returns to the main function when it runs to yield line,previons_line, that is, Previons_line is empty, which executes the output after the main function, and the second call to the search () function, directly from the Previons_ Line.append (line) starts running until the yield line,previons_line is run back to the main function. And so on, so the last line in Somefile.txt, "Python is end." Will not be added to the previons_line.
Python basics: Every step with the yield keyword function call