首页 > 解决方案 > 使用 with open 从另一个文件中提取整数的增量字典

问题描述

我已经坚持了很长一段时间,我做了一些研究,我知道这是因为字典有一个不可散列的问题,但老实说,我需要帮助,你们是最后的手段。基本上有一个字典,其中包含 0 的 id 值。所以有一个包含这些值的日志文件,所以我使用正则表达式来提取它们。我已经把它们变成了一个整数,所以如果我打印它们就不会是一个 str。我需要的是用提取的值增加字典,所以如果找到它们,字典中的值会上升,所以如果找到 10,则为 1102,计数应该是 10,我希望这是有道理的,谢谢!代码:

def finding_matchedevents():
     eventidnew = {1102: {'count': 0}, 4611: {'count': 0}, 4624: {'count': 0}}
     with open('path', 'r') as matchedid:     
         for each_line in matchedid:
             if 'Matched' in each_line:
                 event = re.findall(r'\d+', each_line)
                 res = list(map(int, event)) 
                 eventidnew[res] = eventidnew[res] + 1
                 print(res)

标签: pythonpython-3.xdictionary

解决方案


res是在每一行中找到的 ID列表,而不是单个 ID。您正在使用该列表来访问字典。

此外,你的 dict 的结构是{ID: {'count': count}}你需要修复你的索引。

最后,要仅更新字典中已有的 ID,请添加一个简单的检查:

def finding_matchedevents():
                 [...]
                 res = list(map(int, event))
                 for num in res:
                     if num in eventidnew:
                         eventidnew[num]['count'] += 1
                 [...]

推荐阅读