python - 使用 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)
解决方案
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
[...]
推荐阅读
- json - json自适应卡内的多个if-else
- excel - 如何自动刷新所有工作表
- java - 附加字符串时出现问题,使其环绕Java
- amazon-web-services - 可以克隆具有静态/固定 MAC 地址的 Amazon EC2 实例吗?
- php - 将mysql结果与PHP中的当前时间进行比较
- python - Numpy中的置换矩阵乘法
- apache-nifi - 如何在 nifi 中解析其字段包含分隔值的 csv 文件
- mongodb - MongoDB $lookup 与 $match 和 $eq,对象数组内的匹配值
- python - 使用字符串索引替换字符串中的特定字符
- python - 除了虚拟环境之外,python 中的全局开发依赖项