首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python实现搜过关键词下上文

2012-07-29 
python实现搜过关键词上下文就是grep -B 的功能。要搜索的关键词储存在一个变量中。在文件中查找这个关键词

python实现搜过关键词上下文
就是grep -B 的功能。要搜索的关键词储存在一个变量中。在文件中查找这个关键词的上面两行的内容,并存储在一个变量中,
不知道怎么实现。想过调用系统命令grep,不知道怎么把变量的直传递给grep。。。。
谢谢大家了。

[解决办法]

Python code
#!/usr/bin/env pythonimport reclass GrepLines(object):    def __init__(self, max):        self._max = max        self._array = []            def push(self, line):        if len(self._array) >= self._max:            self._array.pop(0)        self._array.append(line)        def __str__(self):        return ''.join(self._array)def Grep(file, key, count):    gl = GrepLines(count)    with open(file, 'r') as fd:        for line in fd:            rs = re.search(key, line)            if rs:                print gl            else:                gl.push(line)        fd.close()        if __name__ == '__main__':    Grep('test2.txt', r'3.3.31.3', 3)
[解决办法]
~/ cat /tmp/test.txt
line 00
line 01
line 02
line 03
line 04
line 05
line 06
line 07
line 08
line 09
line 10

~/ grep -B 2 "line 1" /tmp/test.txt
line 08
line 09
line 10

Python code
In [1]: import subprocessIn [2]: result = subprocess.check_output(['grep', '-B', '2', 'line 1', '/tmp/test.txt'])In [3]: resultOut[3]: 'line 08\nline 09\nline 10\n'
[解决办法]
[Quote=引用:]
Python code
In [2]: result = subprocess.check_output(['grep', '-B', '2', 'line 1', '/tmp/test.txt'])
[解决办法]
排版烂了,反正就是这句 
grep -B2 $ins $file

热点排行