首页 > 解决方案 > 使用正则表达式组更新 python 字典

问题描述

我正在遍历日志文件,需要使用组内的正则表达式匹配更新字典的值。当我尝试使用 error_msg 1 “我得到 IndexError:列表索引超出范围”。

以下是我匹配的 syslog 文件中的示例行 =

5 月 27 日 11:45:40 ubuntu.local ticky: INFO: Created ticket [#1234] (username)

5 月 24 日 11:44:12 ubuntu.local ticky:错误:检索信息时超时 [#34504](用户名)

5 月 24 日 11:44:12 ubuntu.local ticky:错误:无法连接到数据库 [#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添加键并增加每条消息的计数?

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

在此处输入图像描述

在此处输入图像描述

标签: pythonregexdictionaryregex-group

解决方案


检查日志文件中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

推荐阅读