<p>这将处理数据,并打印所需的输出。我已经尽力在下面的评论中解释清楚了,但是如果有什么不清楚的地方,请提问。在</p>
<pre><code>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)
</code></pre>