加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在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行?

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读