用regex组更新python字典

问题描述 投票:0回答:1

我正在通过一个日志文件进行迭代,需要更新一个字典的值,并将其与一个组内的regex匹配。1 "I get IndexError: list index out of range".

这里是我匹配到的syslog文件中的示例行= =。

5月27日 11:45:40 ubuntu.local ticky: INFO: 创建 ticket [#1234] (用户名)

5月24日 11:44:12 ubuntu.local ticky: ERROR: Timeout while retrieving information [#34504] (username)

5月24日 11:44:12 ubuntu.local ticky: ERROR: 连接数据库失败 [#44514] (用户名)

有另一个字典,"per_user",它工作正常,并为每个用户递增'INFO'和'ERROR'计数。

error = {}
per_user = {}
with open('syslog.log', 'r') as file: #opening the syslog file
    for line in file.readlines():
        pattern1 = r"ticky: INFO: ([\w ]*) " #info message
        pattern2 = r"ticky: ERROR: ([\w ]*) " #error message
        pattern3 = r"(\([\w]*\))$" #username
        info_msg = re.findall(pattern1, line)
        error_msg = re.findall(pattern2, line)
        user = re.findall(pattern3, line)
        for x in user:
            x = x.strip('()')
            if x not in per_user:
                per_user[x] = {'INFO':0,'ERROR':0}
            if info_msg is not None:
                per_user[x]['INFO'] += 1
            if error_msg is not None:
                per_user[x]['ERROR'] += 1  
        if error_msg is not None:
            for errors in error_msg:
                if errors not in error:
                    error[errors] = 0
                error[errors] += 1

    file.close()

为什么我的错误字典没有为error_msg添加键?1 并递增每条消息的计数?

这些都是我的字典将填充参考的示例表。

enter image description here

enter image description here

python regex dictionary regex-group
1个回答
0
投票

检查日志文件中ERROR和INFO后面是否有":"。

希望能帮到你:)

            if x not in per_user:
                per_user[x] = {'INFO':0,'ERROR':0}
            if info_msg != []:
                per_user[x]['INFO'] += 1
            if error_msg != []:
                per_user[x]['ERROR'] += 1  
        if error_msg != []:
            for errors in error_msg:
                if errors not in error:
                    error[errors] = 0
                error[errors] += 1
© www.soinside.com 2019 - 2024. All rights reserved.