python grep之前寻找一个模式然后是一些行

Sim*_*eth 2 python grep lines

我正在寻找相同的 _grep -B14 MMA

我有一个我打开的URL,它吐了很多行.我想要

  1. 找到有'MMa'的行
  2. 然后在它之前打印第14行

我甚至不知道从哪里开始.

import urllib
import urllib2

url = "https://longannoyingurl.com"

opts = {
  'action': 'Dump+It'
}
data = urllib.urlencode(opts)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print  response.read() # gives the full html output
Run Code Online (Sandbox Code Playgroud)

Dan*_*erz 7

而不是仅仅read在响应对象上执行裸操作,readlines而是调用,然后通过每一行运行正则表达式.如果该行匹配,则在其前面打印第14行,但检查您是否没有否定索引.例如

import re

lines = response.readlines()

r = re.compile(r'MMa')
for i in range(len(lines)):
    if r.search(lines[i]):
        print lines[max(0, i-14)]
Run Code Online (Sandbox Code Playgroud)