【问题标题】:Replace network address with host address in python在python中用主机地址替换网络地址
【发布时间】:2016-10-23 20:29:06
【问题描述】:
我有一个带有这种格式的 ip 地址的文件
192.168.1.9
192.168.1.10
192.168.1.8
我读到这样的列表
with open("file.txt") as f:
ipaddr = f.read().splitlines()
然后在上面运行一些函数。
但是,我也可以在此文档中输入网络地址,如
192.168.0.0/25 并以某种方式将它们在列表中翻译为
192.168.0.1
192.168.0.2
192.168.0.3
我什至不知道如何做到这一点? (运行 Python 2.6)
【问题讨论】:
标签:
python
function
ip-address
【解决方案1】:
netaddr 是最好的方法之一:
import netaddr
with open('file.txt') as f:
for line in f:
try:
ip_network = netaddr.IPNetwork(line.strip())
except netaddr.AddrFormatError:
# Not an IP address or subnet!
continue
else:
for ip_addr in ip_network:
print ip_addr
对于示例文件:
10.0.0.1
192.168.0.230
192.168.1.0/29
它给出的输出是:
10.0.0.1
192.168.0.230
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
【解决方案2】:
您需要使用正则表达式解析您的文本文件。在 Python 中查找“re”模块。这个想法的快速实现是:
import re
with open("ips.txt") as f:
ip_raw_list = f.read().splitlines()
#Only takes the string after the '/'
reg_ex_1 = r'(?<=/)[0-9]*'
#Only take the first three numbers "0.0.0" of the IP address
reg_ex_2 = r'.*\..*\..*\.'
ip_final_list = list()
for ip_raw in ip_raw_list:
appendix = re.findall(reg_ex_1, ip_raw)
#Ip with no backslash create on input
if not appendix:
ip_final_list.append(ip_raw)
#Ip with backslash create several inputs
else:
for i in range(int(appendix[0])):
ip_final_list.append(re.findall(reg_ex_2, ip_raw)[0] + str(i))
此代码使用正则表达式的强大功能将“0.0.0.0”形式的 IP 与“0.0.0.0/00”形式的 IP 分开。那么对于第一种形式的IP,你直接把IP放在最后的列表上。对于第二个 for 的 IP,您运行一个 for 循环以将多个输入放入最终列表中。