使用Python从文本文件解析IP地址/网络

2024-09-30 18:16:42 发布

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

我有下面的文本文件,我需要一些帮助解析出IP地址。

文本文件的格式是

abc 10.1.1.1/32   aabbcc
def 11.2.0.0/16   eeffgg
efg 0.0.0.0/0   ddeeff

换句话说,一堆IP网络作为日志文件的一部分存在。输出应如下:

10.1.1.1/32
11.2.0.0/16
0.0.0.0/0

我有下面的代码,但没有输出所需的信息

file = open(filename, 'r')
for eachline in file.readlines():
    ip_regex = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', eachline)
    print ip_regex

Tags: 文件ip网络def格式regexfileabc
2条回答

首先,您的regex甚至不试图捕获任何东西,除了四个点数字,所以它当然不会匹配任何其他东西,比如最后的/32。如果你只是在结尾加上/\d{1,2},它会解决这个问题:

(?:\d{1,3}\.){3}\d{1,3}/\d{1,2}

Regular expression visualization

Debuggex Demo


但是,如果您对正则表达式的理解不足以理解这一点,那么您可能不应该将正则表达式用作永远无法调试或扩展的“魔法”。使用str方法(如splitfind)会更详细一些,但对于新手来说可能更容易理解:

for line in file:
    for part in line.split()
        try:
            address, network = part.split('/')
            a, b, c, d = address.split('.')
        except ValueError:
            pass # not in the right format
        else:
            # do something with part, or address and network, or whatever

另一方面,根据实际使用这些内容的情况,您可能希望使用^{}模块(或the backport on PyPI用于2.6-3.2),而不是字符串解析:

>>> import ipaddress
>>> s = '10.1.1.1/32'
>>> a = ipaddress.ip_network('10.1.1.1/32')

您可以将其与以上任一项结合起来:

for line in file:
    for part in line.split():
        try:
            a = ipaddress.ip_network(part)
        except ValueError:
            pass # not the right format
        else:
            # do something with a and its nifty methods

在这种特殊情况下,regex可能会被过度终止,您可以使用split

with open(filename) as f:
    ipList = [line.split()[1] for line in f]

这将产生一个字符串列表,即ip地址。

相关问题 更多 >