python 文本处理难题。 只能采用Python解决。要求最优效率最高解法,谢谢。
发布网友
发布时间:2022-05-29 19:10
我来回答
共2个回答
热心网友
时间:2023-11-08 19:46
最优效率最高解法是啥?
结果:
C:\>cat.py
['10.0.4', '172.19.3', '192.16.1-2', '192.16.9', '192.16.29', '192.16.99-100', '
192.168.1-3']
代码:
import string
def toNumber(ipStr):
nums=[int(i) for i in ipStr.split(".")]
return rece(lambda x,y:x*256+y,nums)
def fromNumber(i):
s=[]
while i>256:
s.append(i%256)
i/=256
s.append(i)
s.reverse()
s=[str(i) for i in s]
return string.join(s,'.')
def fromArr(arr):
if len(arr)==1:
return fromNumber(arr[0])
else:
return fromNumber(arr[0])+"-"+str(arr[-1]%256)
def convert(fname):
#to number
ips=[toNumber(ip.strip()) for ip in open("cat.txt").readlines()]
ips.sort()
#collect
alen=len(ips)
narr=[]
i=0
last=0
while i+1<alen:
if ips[i+1]-ips[i]>1:
narr.append(ips[last:i+1])
last=i+1
i+=1
narr.append(ips[last:])
#to our special form
return [fromArr(a) for a in narr]
s=convert("cat.txt")
print s
热心网友
时间:2023-11-08 19:47
from itertools import groupby
context = """
192.168.1
192.168.2
192.168.3
172.19.3
192.16.1
192.16.2
10.0.4
192.16.29
192.16.9
192.16.99
192.16.100
"""
for prefix, block in groupby(map(lambda x: x.split('.'),
filter(None, sorted(context.splitlines()))),
lambda x: x[:2]):
range = list(block)
if len(range)==1:
print '.'.join(range[0])
else:
print '.'.join(range[0]) + ' ~ ' + '.'.join(range[-1])