使用with open发出从另一个文件中提取整数的递增字典

2024-10-01 11:35:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在这上面呆了很长一段时间了,我做了一些研究,我知道这是因为字典的一个不好的问题,但老实说,我需要帮助,你们是最后的选择。 基本上得到了一个字典,其中保存有0个ID的值。所以有一个日志文件包含这些值,所以我使用regex来提取它们。我已经把它们变成了一个整数,所以如果我打印它们,它们就不会是str。我需要的是用提取的值来增加字典,这样如果找到它们,字典中的值就会上升,所以1102如果找到10,计数应该是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)

Tags: 文件ineventid字典countlineres
1条回答
网友
1楼 · 发布于 2024-10-01 11:35:46

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
                 [...]

相关问题 更多 >