[英]How do I open up a text file and use it in this code to sort ip adresses python
因此,我没有设置要排序的ip,而是在一个文本文件中有过多的ips,尽管我该如何打开它并查看出现最多的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)"
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地址列表,按从最频繁到最不频繁的顺序排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.