python练习--模拟grep -B功能

测试文件

$ head -20 test.txt 
python
akdfj
adfkjakd
adfka;sdlfk
adfkasdf
kdasfjaslkdf
dfskafjadsl
python
adaksf
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj
dkfsafj

方法一:

$ cat grep_B_1.py 
# -*- encoding = utf-8 -*-

"""
This module supply the same fuction of grep -B N

:param filename
:param pattern
:param maxlen

Usage:

  >>> python grep_B_1.py test.txt python 3

"""

from __future__ import print_function
import sys
import collections

def grep_B(filename, pattern, maxlen=3):
    """
    """
    with open(filename, 'r') as f:
        q = collections.deque(maxlen=int(maxlen))
        for line in f:
            if pattern in line:
                print(''.join(q), end='')
                print(line, end='')
                print('-' * 20)
            q.append(line)

if __name__ == '__main__':
    grep_B(*sys.argv[1:])

测试结果一:

$ python grep_B_1.py test.txt python 3
python
--------------------
adfkasdf
kdasfjaslkdf
dfskafjadsl
python
--------------------

方法二:

$ cat grep_B_2.py 
# -*- encoding = utf-8 -*-

"""
"""

from __future__ import print_function
import sys
import re

def grep_B(filename, pattern, maxlen):
    """
    """
    with open(filename, 'r') as f:
        context = ''.join(f.readlines())
    m = re.compile(r'(
.*){0,3}')
    l = re.split('(.*' + pattern + '.*
)', context)
    for b,a in zip(l[0::2], l[1::2]):
        print(m.match(b[::-1]).group(0)[::-1], end='')
        print(a, end='')
        print('-' * 20)

if __name__ == '__main__':
    grep_B(*sys.argv[1:])
$ python grep_B_2.py test.txt python 3
python
--------------------
adfkasdf
kdasfjaslkdf
dfskafjadsl
python
--------------------
原文地址:https://www.cnblogs.com/sky58/p/8635778.html