在python中等效于grep -B的代码是什么?
发布时间:2020-12-20 11:06:20 所属栏目:Python 来源:网络整理
导读:参见英文答案 cat,grep and cut – translated to python????????????????????????????????????5个 如何使用python从文件中的匹配字符串之前打印n行? man grep -B NUM,–before-context=NUM Print NUM lines of leading context before matching lines. Pla
参见英文答案 >
cat,grep and cut – translated to python????????????????????????????????????5个
如何使用python从文件中的匹配字符串之前打印n行?
解决方法
您只需要保留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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |