使用Python脚本对IP地址进行排序 [英] Sorting IP Addresses in a Python Script

查看:218
本文介绍了使用Python脚本对IP地址进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将要读取的IP地址分类为python脚本并打印出来.我起草的代码读取并打印文件的内容(请参见示例)

I'm trying to sort IP Addresses which I'm reading into a python script and printing out. The code that I've drafted up reads and prints the contents of a file (see example)

#!/usr/bin/python

f = open('file.txt', 'r')
file_contents = f.read()
print (file_contents)
f.close()

我的问题是如何导入IP地址并对其进行正确排序?在命令行上,我通常会通过一个简单的排序命令(sort -n -t.-k 1,1 -k 2,2 -k 3,3 -k 4,4)传递文件.但是,如何考虑到IP的每个八位位组的0-255编号模式,如何让python对从文件中读取的IP进行排序,以便正确地对输出进行排序?

My issue is how do I take that importing of IP Addresses and sort them correctly? At the command line I would normally pass the file through a simple sort command (sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 ). But how can I get python to sort the IPs it's reading from the file so the output is sorted correctly, taking into consideration the 0-255 numbering schema for each octet of an IP?

谢谢

推荐答案

如果您不想使用任何外部软件并且想要一个紧凑的解决方案,则可以始终提供lambda函数作为排序键.

If you do not want to use any external software and want a compact solution, you can always supply a lambda function as sort key.

with open("ip.txt", "r") as infile:
    iplist = sorted([i.strip() for i in infile.readlines()], key = lambda x: int(''.join((lambda a:lambda v:a(a,v))(lambda s,x: x if len(x) == 3 else s(s, '0'+x))(i) for i in x.split('.'))))

这假定ip.txt中的普通IPv4由换行符分隔.

This assumes normal IPv4s in ip.txt separated by a line break.

生成的iplist包含IP的排序列表.您也可以像这样将它们输出到文件中:

The resulting iplist ist a sorted list with the IPs. You can also output them to file like this:

with open("ip.txt", "r") as infile:
    iplist = sorted([i.strip() for i in infile.readlines()], key = lambda x: int(''.join((lambda a:lambda v:a(a,v))(lambda s,x: x if len(x) == 3 else s(s, '0'+x))(i) for i in x.split('.'))))

with open("output.txt", "w") as outfile:
    outfile.write("\n".join(i for i in iplist))

输出文件可以与输入文件相同,也可以不同.

The output file could be the same as the input or a different file.

这篇关于使用Python脚本对IP地址进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆