2 回答

TA贡献1779条经验 获得超6个赞
这将操作您的数据,并打印您想要的输出。我已经尝试在下面的评论中尽可能地解释它,但请提出任何不清楚的问题。
from collections import defaultdict
import socket
# build a dictionary of ip -> set of ports
# default dict is cool becasue if the key doesn't exist when accessed,
# it will create it with a default value (in this case a set)
# I'm using a set because I don't want to add the same port twice
ip_to_ports = defaultdict(set)
with open('mres.txt') as fp:
for line in fp:
# grab only the lines we're interested in
if line.startswith('Host:'):
parts = line.strip().split()
ip = parts[1]
port = parts[-1]
# split it by '/' and grab the first element
port = port.split('/')[0]
# add ip and ports to our defaultdict
# if the ip isn't in the defaultdict, it will be created with
# an empty set, that we can add the port to.
# if we run into the same port twice,
# the second entry will be ignored.
ip_to_ports[ip].add(port)
# sort the keys in ip_to_ports by increasing address
for ip in sorted(ip_to_ports, key=socket.inet_aton):
# sort the ports too
ports = sorted(ip_to_ports[ip])
# create a string and print
ports = ', '.join(ports)
print(ip, ports)
添加回答
举报