Python字典 - 在下一行找到键

我从电子邮件正文创建了字典


print email body


Application name: dummy.service

Source: host2

Timestamp: 2019-01-23T22:00:01.026Z

Message: LivePnL:in live pricing



Application name: dummy.service

Source: host2

Timestamp: 2019-01-23T22:00:01.016Z

Message: Risk request failed



Application name: dummy.service

Source: host2

Timestamp: 2019-01-23T22:00:00.994Z

Message: 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 中的行放入单行?


富国沪深
浏览 125回答 2
2回答

翻过高山走不出你

segment = line.split(' ')您需要使用多个分隔符分割行,而不仅仅是空格 (' ') 分隔符。为此,您需要正则表达式。import re segment = re.split(' |\n',line)这应该会给你想要的结果。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python