0

因此,我没有设置 ips 进行排序,而是在一个文本文件中有大量它们需要排序,但如何打开它并查看哪些出现最多?

#!/usr/bin/python

import iplib

ips = []

for ip in ["192.168.100.56", "192.168.0.3", "192.0.0.192", "8.0.0.255"]:
       ips.append(iplib.IPv4Address(ip))

def ip_compare(x, y):
       return cmp(x.get_dec(), y.get_dec())

ips.sort(ip_compare)

print [ip.address for ip in ips]

文本文件看起来像这样

113.177.60.181 - - [05/Jul/2013:03:27:07 -0500] "GET /email/13948staticvoid.gif HTTP/1.1" 200 17181 "http://www.bereans.org/email/index.php" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"
113.177.60.181 - - [05/Jul/2013:03:27:07 -0500] "GET /email/13948staticvoid.gif HTTP/1.1" 200 17181 "http://www.bereans.org/email/index.php" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"
4

1 回答 1

0
from collections import Counter
with open('path/to/file') as infile:
    counts = Counter(line.split('-', 1)[0].strip() for line in infile)
IPs = counts.most_common() # thanks @Jon Clements
# equivalent to IPs = sorted(counts, key=counts.__getitem__, reverse=True)

给你!IPs现在在您的文本文件中有一个 IP 地址列表,按从最频繁到最不频繁的顺序排序

于 2013-07-22T00:35:23.393 回答