Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中与grep-B等价的代码是什么?_Python_Python 3.x - Fatal编程技术网

python中与grep-B等价的代码是什么?

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:

如何使用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:
                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='')
,是的:)到目前为止最好的答案