使用Python3(如果需要可以使用Python2)
利用内置库ipaddress
和groupby
以及其他内置好用的工具:
创建一个将IP地址对象列表转换为范围的函数:
def create_range(ip_addresses):
groups=[]
for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i,x):i-int(x)):
group = map(operator.itemgetter(1), g)
if len(group) > 1:
groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))
else:
groups.append(str(group[0]))
return groups
导入所需的库,从csv中解析出值(使用StringIO
模拟读取文件):
import csv
import ipaddress
import io
import operator
import itertools
import collections
ips = defaultdict(list)
csv_file = u"""Data_Center_Name, IP
DC_1, 50.102.182.2
DC_1, 52.102.182.4
DC_1, 52.102.182.1
DC_1, 52.102.182.5
DC_1, 52.102.182.3
DC_1, 27.101.178.17
DC_1, 27.101.178.16
DC_1, 27.101.178.15
DC_1, 23.201.165.7
DC_2, 55.200.162.10
DC_2, 55.200.162.12
DC_2, 55.200.162.13
DC_2, 55.200.162.11
DC_3, 30.101.102.4
"""
with io.StringIO(csv_file) as f:
reader = list(csv.reader(f))
for (dc, ip) in reader[1:]:
ip = ipaddress.IPv4Address(unicode(ip.strip()))
ips[dc.strip()].append(ip)
result = {dc: create_range(ip_range) for dc, ip_range in ips.items()}
结果:
In [92]: result
Out[92]:
{'DC_1': ['23.201.165.7',
'27.101.178.15-17',
'50.102.182.2',
'52.102.182.1',
'52.102.182.3-5'],
'DC_2': ['55.200.162.10-13'],
'DC_3': ['30.101.102.4']}
Python2
import csv
import ipaddress
from StringIO import StringIO
import operator
import itertools
import collections
def create_range(ip_addresses):
groups=[]
for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i,x):i-int(x)):
group = map(operator.itemgetter(1), g)
if len(group) > 1:
groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))
else:
groups.append(str(group[0]))
return groups
ips = collections.defaultdict(list)
csv_file = """Data_Center_Name, IP
DC_1, 50.102.182.2
DC_1, 52.102.182.4
DC_1, 52.102.182.1
DC_1, 52.102.182.5
DC_1, 52.102.182.3
DC_1, 27.101.178.17
DC_1, 27.101.178.16
DC_1, 27.101.178.15
DC_1, 23.201.165.7
DC_2, 55.200.162.10
DC_2, 55.200.162.12
DC_2, 55.200.162.13
DC_2, 55.200.162.11
DC_3, 30.101.102.4
"""
reader = csv.reader(StringIO(csv_file))
next(reader)
for (dc, ip) in reader:
ip = ipaddress.IPv4Address(unicode(ip.strip()))
ips[dc.strip()].append(ip)
result = {dc: create_range(ip_range) for dc, ip_range in ips.items()}
使用 Py2 代码的结果
print result
{'DC_2': ['55.200.162.10-13'], 'DC_3': ['30.101.102.4'], 'DC_1': ['23.201.165.7', '27.101.178.15-17', '50.102.182.2', '52.102.182.1', '52.102.182.3-5']}
做得好!谢谢。是否可能获得输出:{'DC_2': ['55.200.162.10-55.200.162.13'], 'DC_3': ['30.101.102.4'], 'DC_1': ['23.201.165.7', '27.101.178.15-27.101.178.17', '50.102.182.2', '52.102.182.1', '52.102.182.3-52.102.182.5']} –
是的,请更改这一行:
groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))
到这个:
groups.append("{}-{}".format(group[0], group[-1]))
locals
)。您是否考虑使用dict
代替? - Snakes and Coffee52.102.182.2
并不存在,但是如果你想说的是将 s/52/50/,那么确实存在50.102.182.2
。 - salparadise