简体   繁体   English

如何从字典键“Message”中提取第一个 IP 地址,并使用提取的 IP 地址添加一个名为“IP”的新键?

[英]How to extract the first IP address from a dictionary key “Message” and add a new key called “IP” with the extracted IP address?

So I have a list with dictionaries inside which I generated from a log file.所以我有一个列表,里面有我从日志文件生成的字典。 I want to create a new key called "IP" with the extracted IP address from "Message"我想使用从“消息”中提取的 IP 地址创建一个名为“IP”的新密钥

This is an example of the list of dictionaries.这是字典列表的示例。

[{'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'}]

I thought of using regex but i get an error saying my dictionary changed sized during iteration.我想过使用正则表达式,但我收到一个错误,说我的字典在迭代期间改变了大小。

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 .您不需要遍历字典,因为您知道密钥,只需从密钥Message的 IP 创建新的。

  • I remove the \s in the regex because you don't want the space我删除了正则表达式中的\s ,因为你不想要空间
  • r"[0-9]{1,3}(?:\.[0-9]{1,3}){3} better regex that check digit group are length [1-3] r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}更好的正则表达式检查数字组的长度为[1-3]
  • use [0] at the end to get the first IP from Message , if you want a list of all the IP found, remove it最后使用[0]Message获取第一个 IP ,如果您想要找到所有 IP 的列表,请将其删除

In case there is no IP, you should first compute the IPs, then add the mapping regarding the result of findall如果没有 IP,则应先计算 IP,然后添加有关findall结果的映射

for value in data:
    ips = re.findall(r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}", value['Message'])
    if ips:
        value["host/IP address"] = ips[0]

If you want to put empty string in case of no IP如果您想在没有 IP 的情况下放置空字符串

for value in data:
    ips = re.findall(r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}", value['Message'])
    value["host/IP address"] = ips[0] if ips else ""

  • with [0] : 'host/IP address': '163.27.187.39'[0]'host/IP address': '163.27.187.39'

  • without [0] : 'host/IP address': ['163.27.187.39', '163.27.187.39']没有[0] : 'host/IP address': ['163.27.187.39', '163.27.187.39']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM