Python字典-在下一行中找到键

时间:2019-01-24 18:16:21

标签: python dictionary key

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

print email body

Application name: Clarion.Pricing.Grid.Service
Source: EC2AMAZ-ITEJKDI
Timestamp: 2019-01-23T22:00:01.026Z
Message: LivePnL:in live pricing


Application name: Clarion.Pricing.Grid.Service
Source: EC2AMAZ-ITEJKDI
Timestamp: 2019-01-23T22:00:01.016Z
Message: Risk request failed


Application name: Clarion.Pricing.Grid.Service
Source: EC2AMAZ-ITEJKDI
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  Clarion prod 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:', 'Clarion.Pricing.Grid.Service']}

如何在Source和Message之后获取值?或如何将email_body中的行放入单行中?

2 个答案:

答案 0 :(得分:0)

您仅呼叫parse_subject(line) if 'Application name' in line。显然,这只会返回包含应用程序名称的行。如果您还想分析源代码行和消息行,我认为您需要删除if语句。或者,您可以添加更多if语句,例如if 'Source' in line: parse_subject(line)

答案 1 :(得分:0)

段= line.split('')

您需要使用多个定界符而不是空格('')分隔符来分隔行。

为此,您需要正则表达式。

导入 segments = re.split('| \ n',line)

这应该给您想要的结果。