如何使用python从文件中的匹配字符串之前打印n行?
解决方法 您只需要保留N个最后一行的缓冲区(列表),然后在遇到匹配时打印它们.man grep
-B NUM,–before-context=NUM
Print NUM lines of leading context before matching lines. Places a
line containing a group separator (–) between contiguous groups of
matches. With the -o or –only-matching option,this has no effect and
a warning is given.我有grep -A的代码:
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('---')
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)总结
以上是内存溢出为你收集整理的在python中等效于grep -B的代码是什么?全部内容,希望文章能够帮你解决在python中等效于grep -B的代码是什么?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)