首页 / PYTHON / python实现ip查询示例
python实现ip查询示例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python实现ip查询示例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1999字,纯文字阅读大概需要3分钟。
内容图文
以下代码实现了ip查询功能
处理程序
import os,time
def getip(filepath):
ip2city={}
file=open(filepath,‘r‘)
lines=file.readlines()
file.close()
for line in lines:
ip=line.split(‘ ‘)[0]
city=line.split(‘ ‘)[1]
haship=hashm(ip)
if haship in ip2city:
pass
else:
ip2city[haship]=city
print(‘Hash done!‘)
return ip2city
def hashm(ip):
iplist=ip.split(‘.‘)
ip=int(iplist[0])*4+int(iplist[1])*2+int(iplist[2])
return ip
def getcityfromip(filepath,ipandcity):
outputstr=[]
for file in os.listdir(filepath):
file_handler=open(filepath+‘\\‘+file,‘r‘)
line=file_handler.readline()
while line:
ip=hashm(line.rstrip())
if ip in ipandcity:
outputstr.append(line.rstrip()+‘ ‘+ipandcity[ip])
line=file_handler.readline()
file_handler.close()
outfile_handler=open(filepath+‘\\‘+file.split(‘.‘)[0]+‘_out.txt‘,‘a+‘)
outfile_handler.writelines(outputstr)
outfile_handler.close()
print(file.split(‘.‘)[0]+‘_out.txt‘+‘done!‘)
def splitfile(filepath):
file=open(filepath,‘r‘)
block_size=8000000
filecount=1
temp=[]
count=0
line=file.readline()
while line or temp:
if count==block_size:
wfile=open(‘D:\\ipfile\\file_‘+str(filecount)+‘.txt‘,‘a+‘)
wfile.writelines(temp)
temp=[]
count=0
wfile.close()
filecount+=1
print(‘Split‘+str(filecount)+‘ done!‘)
else:
count+=1
temp.append(line)
line=file.readline()
file.close()
return os.path.join(‘D:\\‘+‘ipfile‘)
if __name__ == ‘__main__‘:
start=time.clock()
filepath=‘D:\\ip.txt‘
ippath=‘D:\\citys.txt‘
ip2city=getip(ippath)
splitfilepath=splitfile(filepath)
getcityfromip(‘D:\\‘+‘ipfile‘,ip2city)
end=time.clock()
print(end-start)
生成IP
#Generate 100 millon ip
import random
import time
def generateIpAdd(file,num):
ip=[]
file=open(file,‘a+‘)
for i in range(num):
ipAdd=‘192.168.‘+str(random.randint(0,255))+‘.‘+str(random.randint(0,255))
ip.append(ipAdd+‘\n‘)
file.writelines(ip)
file.close()
if __name__==‘__main__‘:
start=time.clock()
for i in range(10000):
generateIpAdd(‘D:\ip.txt‘,10000)
end=time.clock()
print(end-start)
原文:http://www.jb51.net/article/48459.htm
内容总结
以上是互联网集市为您收集整理的python实现ip查询示例全部内容,希望文章能够帮你解决python实现ip查询示例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。