python练习--模拟grep -B功能
生活随笔
收集整理的這篇文章主要介紹了
python练习--模拟grep -B功能
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
測試文件
$ 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 maxlenUsage:>>> python grep_B_1.py test.txt python 3"""from __future__ import print_function import sys import collectionsdef 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:])測試結(jié)果一:
$ 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 redef grep_B(filename, pattern, maxlen):""""""with open(filename, 'r') as f:context = ''.join(f.readlines())m = re.compile(r'(\n.*){0,3}')l = re.split('(.*' + pattern + '.*\n)', 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 --------------------?
轉(zhuǎn)載于:https://www.cnblogs.com/sky58/p/8635778.html
總結(jié)
以上是生活随笔為你收集整理的python练习--模拟grep -B功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windbg调试
- 下一篇: Python Numpy 笔记