Как то так.
from __future__ import print_function
def get_lines( some_file, start_rule, end_rule, process=print ):
line_iter= enumerate( source )
for n, text in line_iter:
if start_rule( n, text ):
process( text )
break
for n, text in line_iter:
process( text )
if end_rule( n, text ): break
Тогда вы можете определить множество мелких функций:
def match_page_5( n, text ):
return re.match( '^Page 5:', text )
def match_line( n, text ):
return line == n
Или сохраняющие состояние, вызываемые объекты
class Match_Pattern( collections.Callable ):
def __init__( self, pattern ):
self.pat= re.compile( pattern )
def __call__( self, n, text ):
return self.pat.match( text )
class Match_Lines_Post_Pattern( collections.Callable ):
def __init__( self, pattern, lines ):
self.pat= re.compile( pattern )
self.lines= lines
self.saw_it= None
def __call__( self, n, text ):
if self.saw_it:
if n == self.saw_it + self.lines
return True
if self.pat.match( text ):
self.saw_it = n
Вы можете создать синтаксический сахар с помощью таких функций.
def sed_by_pattern( filename, pattern1, pattern2 ):
with open(filename,'r') as source:
get_lines( source, lambda n,tx: re.match(pattern1,tx), lambda n,tx: re.match(pattern2,tx) )
Это приведет вас к функции, подобной следующей
Это использование так же просто, как команда SED с дополнительной пунктуацией.
sed_by_pattern( some_file, '^Page 5:', '^Page 6:' )
Или этот кусочек сахара ...
def sed_by_matcher( filename, matcher1, matcher2 )
with open(filename, 'r') as source:
get_lines( source, matcher1, matcher2 )
Это использование так же просто, как команда SED с дополнительной пунктуацией.
see_by_matcher( some_file, match_line(100), Match_Lines_Post_Pattern( '^Page 10:', 3 ) )