受到
falsetru的答案启发,我重写了代码,使其更加通用。
现在要探索的文件:
.
import re,glob
from itertools import ifilter
from os import getcwd,listdir,path
from inspect import isfunction
regx = re.compile('^[^\n]*word1.*?word3.*?$',re.S|re.M)
G = '\n\n'\
'MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW\n'\
'MWMWMW %s\n'\
'MWMWMW %s\n'\
'%s%s'
def search(REGX, how_to_find_files, dirpath='',
G=G,sepm = '\n======================\n'):
if dirpath=='':
dirpath = getcwd()
if isfunction(how_to_find_files):
gen = ifilter(how_to_find_files,
ifilter(path.isfile,listdir(dirpath)))
elif isinstance(how_to_find_files,str):
gen = glob.glob(path.join(dirpath,
how_to_find_files))
for fn in gen:
with open(fn) as fp:
found = REGX.findall(fp.read())
if found:
yield G % (dirpath,path.basename(fn),
sepm,sepm.join(found))
def select(fn):
return fn[-4:]=='.txt'
print ''.join(search(regx, select))
print ''.join(search(regx,'*.txt'))
通过一系列生成器的连续处理链接多个文件的优点在于,最终使用
''.join()
进行连接会创建一个唯一的字符串,可以立即写入,而如果没有这样处理,则依次打印多个单独的字符串需要更长的时间,因为需要中断显示(我表达清楚了吗?)