首页 > 编程 > Python > 正文

python实现ip查询示例

2020-02-23 05:16:33
字体:
来源:转载
供稿:网友

以下代码实现了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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表