Python中的grep等价物是什么?

2024-04-20 07:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个写着“我喜欢大象”的文本文件。 如果我把所说的文件和管道猫到'grep大象',我得到整个行“我喜欢大象”。

如何使用re在Python中实现此功能? 我一直在试着:

test = re.search('elephants', 'I like elephants.\nThey are nice')
test.group(0)

我只得到“大象”这个词,而不是整个句子作为输出。

我怎么得到整句话? 谢谢您。


Tags: 文件test功能research管道groupgrep
1条回答
网友
1楼 · 发布于 2024-04-20 07:26:18

您可以使用in关键字检查子字符串:

with open('text_file.txt', 'r') as f:
    for line in f.readlines():
        if 'elephant' in line:
            print(line)

或者,如果字符串s包含\n个字符:

for line in s.split('\n'):
    if 'elephant' in line:
        print(line)

你的regex只打印elephant,因为这就是它捕获的:正是你的regex字符串。如果要改为使用以下regex:

test = re.search(r'(.*?elephants.*?)\n', 'I like elephants.\nThey are nice')

然后你会得到test.group(0)test.group(1)的结果,包括大象前后的整条线。

In [22]: test.group(0)
Out[22]: 'I like elephants.\n'

那是整个被俘的绳子。

In [23]: test.group(1)
Out[23]: 'I like elephants.'

这只是捕获组(括号中的字符串)。

相关问题 更多 >