国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現ip查詢示例

2019-11-25 18:28: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
            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)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高清| 富顺县| 阿城市| 桐乡市| 长泰县| 保靖县| 罗源县| 锦屏县| 青田县| 广南县| 山丹县| 华阴市| 康平县| 阿拉善右旗| 无极县| 汪清县| 若尔盖县| 井研县| 南江县| 绥化市| 安顺市| 鹤壁市| 河津市| 都匀市| 林周县| 泽库县| 浪卡子县| 黑龙江省| 大同县| 建平县| 张家川| 高阳县| 峨边| 万山特区| 尼勒克县| 湟中县| 龙岩市| 龙里县| 灵山县| 金堂县| 永登县|