与python中的grep -B等价的代码是什么?

时间:2018-07-19 08:06:10

标签: python python-3.x

如何使用python从文件中的匹配字符串前打印n行?

  

man grep

     
    

-B NUM,--before-context = NUM​​

         

在匹配的行之前打印前导上下文的NUM行。放置一个     连续的组之间包含组分隔符(-)的行     火柴。使用-o或--only-matching选项,此选项无效,并且     警告。

  

我有grep -A的代码:

def grepA(word,file,num=0):
    with open(file) as f:
        for line in f:
            if word in line:
                print(line + ''.join(islice(file, num)))
                print('---')

2 个答案:

答案 0 :(得分:4)

您只需要保留最后N行的缓冲区(列表),然后在遇到匹配项时打印它们。

context_lines = []
for line in f:
    context_lines.append(line)
    if len(context_lines) > 5:  # Too many lines?
        context_lines.pop(0)  # Pop the first one off.
    if word in line:
        # context_lines already includes the `line` we're looking at
        for ctx_line in context_lines:  
             print(ctx_line)

答案 1 :(得分:2)

您需要缓存行:

def grepb(word,file, num=0):
    if num == 0:
        print(re.findall(re.compile(word), line)[0])  # https://stackoverflow.com/questions/26659142
    else:
        cache = collections.deque([], num)
        with open(file) as f:
            for line in f:
                cache.append(line)
                if word in line:
                    print('\n'.join(cache))
                    print('---')