【问题标题】:How can I search a range of lines in python?如何在 python 中搜索一系列行?
【发布时间】:2013-10-30 09:39:40
【问题描述】:

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

sed -rn '/03.Nov.2012/,/12.Oct.2013/s/search key/search key/p' my.log

以上将仅显示 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.'

但这让我觉得不是“pythonic”。

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

【问题讨论】:

    标签: python regex sed


    【解决方案1】:

    使用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
    

    【讨论】:

    • 我只是在写一个dropwhile 解决方案,但你抢先了。
    • 也许是不同的问题,但我怎样才能将这些 lambda 表达式转换为布尔正则表达式匹配?
    • @Jamie 你只需要lambda L: re.search(r'03\.Nov\.2012', L) 这将导致None 不匹配或MatchObject
    • 实际上,您的解决方案是我的python hack 所做的,而不是sed 表达式所做的;有没有一种简单的方法可以在takewhile() 中包含直到日期字符串的末尾,而不是在第一次出现后省略所有内容。
    • @Jamie well None 在布尔意义上是虚假的,而 MatchObject 是真实的......所以只是搜索的结果很好 - 它不需要与任何东西进行比较
    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    相关资源
    最近更新 更多