gpt4 book ai didi

python - 当文本位于变量内部时,正则表达式返回每行匹配的文本

转载 作者:行者123 更新时间:2023-12-01 05:28:58 25 4
gpt4 key购买 nike

如何在 Python 中制定正则表达式,以类似 grep 的方式返回找到模式的行?假设我有以下文本(使用 subprocess 调用的 shell 命令的输出),分配给名为输出的变量:

output = "Lorem Ipsum is simply dummy text.\nLorem Ipsum has been the industry's standard\nIt has survived not only five centuries\nIt was popularised in the 1960s with the release of"

(抱歉长度问题,但它更接近真实的示例。所以现在的挑战是根据 \n 分割字符串,然后独立搜索每一行。所以,我们可以从

output_lines = re.split(r'\n', output)

并获取一个列表,其中每个元素都是一行。我们现在有:

 >>> print output_lines
['Lorem Ipsum is simply dummy text.',
'Lorem Ipsum has been the industry's standard',
'It has survived not only five centuries',
'It was popularised in the 1960s with the release of']

您建议我如何在 output_lines 中搜索包含我请求的模式(例如“Lorem”)的行?

我尝试了显而易见的方法:

for line in output_lines:
if re.search(r"Lorem",line):
print line

而且它有效。但是,有人知道更紧凑(并且可能更优雅)的方法来完成此任务吗?

最佳答案

一个简单的衬里是:

output_lines = [i for i in re.split(r'\n', output) if "Lorem" in i]
print output_lines

输出:

['Lorem Ipsum is simply dummy text.', "Lorem Ipsum has been the industry's standard"]

事实上:正则表达式太过杀伤力,但是如果您需要正则表达式:

output_lines = [i for i in re.split(r'\n', output) if re.search("Lorem",i)]

关于python - 当文本位于变量内部时,正则表达式返回每行匹配的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com