因此,我没有设置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)"
答案 0 :(得分: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地址列表,按照从最常见到最不频繁的顺序排序