在python中等效于grep -B的代码是什么?

在python中等效于grep -B的代码是什么?,第1张

概述参见英文答案 > cat, grep and cut – translated to python                                    5个 如何使用python从文件中的匹配字符串之前打印n行? man grep -B NUM, –before-context=NUM Print NUM lines of leading context before match 参见英文答案 > 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. 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('---')
解决方法 您只需要保留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)
总结

以上是内存溢出为你收集整理的在python中等效于grep -B的代码是什么?全部内容,希望文章能够帮你解决在python中等效于grep -B的代码是什么?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1192112.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存