仅保留 python 字符串中单词的第一次出现

Retain only first occurence of a word in python string

在逐行阅读文本时,我在 python 中将以下文本作为字符串。有些线路可以有超过 1 个警报,有些线路只能有 1 个,有些线路甚至没有警报。

line = process:process_name, Alert:problem with record 44, Alert:problem with record 134, Alert: problem with record 22.

如果我在给定行中有超过 1 个警报,我必须像下面那样组合所有警报。

预期输出:

new_line = process:process_name, Alert:problem with record 44,problem with record 134,problem with record 22.

python有没有办法做到这一点?

我尝试使用字符串拆分并识别以 Alert 开头的拆分。但不确定之后如何进行。

一种方法,使用 re.findall 查找所有警报,然后连接以构建您想要的输出字符串:

inp = "line = process:process_name, Alert:problem with record 44, Alert:problem with record 134, Alert: problem with record 22."
start = inp.split('Alert:', 1)[0]
alerts = re.findall(r'Alert:\s*(problem with record \d+)', inp)
output = start + 'Alert:' + ','.join(alerts)
print(output)

这会打印:

line = process:process_name, Alert:problem with record 44,problem with record 134,problem with record 22