zoukankan      html  css  js  c++  java
  • 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
    --------------------
  • 相关阅读:
    MySQL集群常见高可用方案(转)
    upsource使用
    Hystrix 使用
    astah UML 先画图、后编程
    java ThreadLocal 使用
    Java基础 Annotation使用
    LVS+Keepalived+Nginx+Tomcat高可用负载均衡集群配置
    招聘求职学习
    Rotate List 面试题
    vue前台(四点二)
  • 原文地址:https://www.cnblogs.com/sky58/p/8635778.html
Copyright © 2011-2022 走看看