我从电子邮件正文创建了字典print email bodyApplication name: dummy.serviceSource: host2Timestamp: 2019-01-23T22:00:01.026ZMessage: LivePnL:in live pricingApplication name: dummy.serviceSource: host2Timestamp: 2019-01-23T22:00:01.016ZMessage: Risk request failedApplication name: dummy.serviceSource: host2Timestamp: 2019-01-23T22:00:00.994ZMessage: Risk request failed如果以上所有内容都在同一行,我可以获得应用程序名称、来源和消息,但如果来源和消息在新行中,我只能获得应用程序名称上面的变量(电子邮件正文)是下面函数的输入def parse_subject(line): info = {} segments = line.split(' ') info['time'] = segments for i in range(2, len(segments)): key = '' if segments[i] == 'Application Name:': key = 'alarm' elif segments[i] == 'Source:': key = 'job' elif segments[i] == 'Message:': key = 'machine' if key != '': i += 1 info[key] = segments[i] return info if mail["Subject"].find("Alert for dummy services errors") > 0 : body = get_autosys_body(mail) for line in body.splitlines(): if 'Application name' in line: job_info = parse_subject(line) break print (job_info)工作信息目前只给我第一行的钥匙{'time': ['Application', 'name:', 'dummy.service']}如何在 Source 和 Message 之后获取值?或者如何将 email_body 中的行放入单行?
2 回答

翻过高山走不出你
TA贡献1875条经验 获得超3个赞
segment = line.split(' ')
您需要使用多个分隔符分割行,而不仅仅是空格 (' ') 分隔符。
为此,您需要正则表达式。
import re segment = re.split(' |\n',line)
这应该会给你想要的结果。
添加回答
举报
0/150
提交
取消