python中与grep-B等价的代码是什么?
如何使用python在文件中匹配字符串之前打印n行 曼格瑞普 -B NUM,--before context=NUM 在匹配行之前打印前导上下文的行数。放置 在连续的组之间包含组分隔符(--)的行 比赛。对于-o或--only匹配选项,这没有效果,并且 发出警告 我有grep-A的代码:python中与grep-B等价的代码是什么?,python,python-3.x,Python,Python 3.x,如何使用python在文件中匹配字符串之前打印n行 曼格瑞普 -B NUM,--before context=NUM 在匹配行之前打印前导上下文的行数。放置 在连续的组之间包含组分隔符(--)的行 比赛。对于-o或--only匹配选项,这没有效果,并且 发出警告 我有grep-A的代码: def grepA(word,file,num=0): with open(file) as f: for line in f: if word in line:
def grepA(word,file,num=0):
with open(file) as f:
for line in f:
if word in line:
print(line + ''.join(islice(file, num)))
print('---')
您只需保留最后N行的缓冲区(列表),然后在遇到匹配时打印它们
context_lines = []
for line in f:
context_lines.append(line)
if len(context_lines) > 5: # Too many lines?
context_lines.pop(0) # Pop the first one off.
if word in line:
# context_lines already includes the `line` we're looking at
for ctx_line in context_lines:
print(ctx_line)
您需要缓存这些行:
def grepb(word,file, num=0):
if num == 0:
print(re.findall(re.compile(word), line)[0]) # https://stackoverflow.com/questions/26659142
else:
cache = collections.deque([], num)
with open(file) as f:
for line in f:
cache.append(line)
if word in line:
print('\n'.join(cache))
print('---')
@vishes_shell:有趣的链接。对于
-A
和-B
,该解决方案是如何工作的?我会使用历史记录为5(效率更高)的deque
,当然,这也会起作用。:)这是可行的,但控制台中的输出会添加源中没有的空格file@VladimirSmith如果line
s已经包含换行符,那么您需要打印(ctx\u line,end='')
,是的:)到目前为止最好的答案