我從電子郵件正文創(chuàng)建了字典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如果以上所有內(nèi)容都在同一行,我可以獲得應(yīng)用程序名稱、來(lái)源和消息,但如果來(lái)源和消息在新行中,我只能獲得應(yīng)用程序名稱上面的變量(電子郵件正文)是下面函數(shù)的輸入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 回答

翻過(guò)高山走不出你
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
segment = line.split(' ')
您需要使用多個(gè)分隔符分割行,而不僅僅是空格 (' ') 分隔符。
為此,您需要正則表達(dá)式。
import re segment = re.split(' |\n',line)
這應(yīng)該會(huì)給你想要的結(jié)果。
添加回答
舉報(bào)
0/150
提交
取消