如何在python中搜索一系列行?

Jam*_*mie 3 python regex sed

我想在两个日期之间搜索日期排序日志文件中的一系列行.如果我在命令行,sed将会派上用场:

sed -rn '/03.Nov.2012/,/12.Oct.2013/s/search key/search key/p' my.log
Run Code Online (Sandbox Code Playgroud)

以上内容仅显示2012年11月3日至2013年10月12日期间包含字符串" search key"的行.

我能做到这么轻便python吗?

我可以为上面建立一个单独的RE,但它会是噩梦.

我能想到的最好的是:

#!/usr/bin/python

start_date = "03/Nov/2012"
end_date = "12/Oct/2013"

start = False

try:
    with open("my.log",'r') as log:
        for line in log:
            if start:
                if end_date in line:
                    break
            else:
                if start_date in line:
                    start = True
                else:
                    continue
            if search_key in line:
                print line

except IOError, e:
    print '<p>Log file not found.'
Run Code Online (Sandbox Code Playgroud)

但这让我觉得不是'pythonic'.

可以假设搜索日期限制将在日志文件中找到.

Jon*_*nts 5

使用itertools和生成器是一种方式:

from itertools import takewhile, dropwhile

with open('logfile') as fin:
    start = dropwhile(lambda L: '03.Nov.2012' not in L, fin)
    until = takewhile(lambda L: '12.Oct.2013' not in L, start)
    query = (line for line in until if 'search string' in line)
    for line in query:
        pass # do something
Run Code Online (Sandbox Code Playgroud)