所以现在我正在文件中查找某些内容。我得到一个 value
变量,它是一个相当长的字符串,带有换行符等。然后,我使用 re.findall(regex, value) 来查找正则表达式。正则表达式相当简单 - 类似于“abc de.*”。
现在,我不仅要捕获正则表达式所具有的任何内容,还要捕获上下文(与 grep
的 -C
标志完全相同)。
因此,假设我将 value
转储到文件并对其运行 grep,我要做的是 grep -C N 'abc de .*' valueinfile
如何在 Python 中实现同样的效果?我需要使用 Unicode 正则表达式/文本的答案。
最佳答案
我的方法是将文本 block 拆分为行列表。接下来,迭代每一行并查看是否有匹配项。如果匹配,则收集上下文行(当前行之前和之后发生的行)并返回它。这是我的代码:
import re
def grep(pattern, block, context_lines=0):
lines = block.splitlines()
for line_number, line in enumerate(lines):
if re.match(pattern, line):
lines_with_context = lines[line_number - context_lines:line_number + context_lines + 1]
yield '\n'.join(lines_with_context)
# Try it out
text_block = """One
Two
Three
abc defg
four
five
six
abc defoobar
seven
eight
abc de"""
pattern = 'abc de.*'
for line in grep(pattern, text_block, context_lines=2):
print line
print '---'
输出:
Two
Three
abc defg
four
five
---
five
six
abc defoobar
seven
eight
---
seven
eight
abc de
---
关于Python 相当于 'grep -C N' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34045227/