因此,我有一个列表,其中包含从日志文件生成的字典。我想使用从“消息”中提取的IP地址创建一个名为“ IP”的新密钥。
这是词典列表的示例。
[{'Date': 'Jun 29', 'Time': '03:22:22', 'PID': '13251', 'Message': 'Authentication failed from 163.27.187.39 (163.27.187.39): Permission denied in replay cache code', 'Access Type': 'Success'}
...
{'Date': 'Jun 29', 'Time': '03:22:22', 'PID': '13263', 'Message': 'connection from 61.74.96.178 () at Wed Jun 29 03:22:22 2005', 'Access Type': 'Success'}]
我曾想过使用正则表达式,但遇到错误,说我的字典在迭代过程中改变了大小。
for Dict in data:
for k,v in Dict.items():
if k == 'Message':
re.findall(r"[0-9]+(?:\.[0-9]+){3}\s", v)
Dict["host/IP address"] = re.findall(r"[0-9]+(?:\.[0-9]+){3}\s", v)
else:
Dict["host/IP address"] = ""
print(Dict)
You don't need to iterate over the dict, as you know the keys, just create the new one from the IP of key
Message
.\s
in the regex because you don't want the spacer"[0-9]{1,3}(?:\.[0-9]{1,3}){3}
better regex that check digit group are length[1-3]
[0]
at the end to get the first IP fromMessage
, if you want a list of all the IP found, remove itIn case there is no IP, you should first compute the IPs, then add the mapping regarding the result of
findall
with
[0]
without
[0]
尝试使用以下代码: