python实现查询_python实现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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值