grep -v 的 Python 等价物是什么?

ixt*_*lix 17 grep python text-processing regular-expression

我喜欢grep -v。我用它所有的时间。但我也在用 python 做一些文本处理,我缺少一件至关重要的事情。

通常,我grep -v习惯从文本中去除无关的东西。

例如,

$ grep -v '[a-z]'
# (I manually review this output to confirm that I don't want those lines)

$ grep '[a-z]' > linesiwanted
Run Code Online (Sandbox Code Playgroud)

但是如何在 Python 中匹配正则表达式的补码?例如,\w?

Arc*_*ege 20

Python 中的正则表达式,无论是search或match方法,返回一个Match对象或None。对于grep -v等效的,您可以使用:

import re
for line in sys.stdin:
    if re.search(r'[a-z]', line) is None:
        sys.stdout.write(line)
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

import re; sys.stdout.writelines([line for line in sys.stdin if re.search(r'[a-z]', line) is None])
Run Code Online (Sandbox Code Playgroud)