使用二分法查找mobile文件中区号归属地

时间:2023-03-09 04:23:35
使用二分法查找mobile文件中区号归属地
#!/usr/bin/env python
#coding:utf-8
'''
Created on 2015年12月8日 @author: DL @Description: 使用二分法查找mobile文件中区号归属地
'''
import os
import sys class SearchAreacode(object): def __init__(self,file_name='mobile_sort'):
self.fp = open(file_name)
self.fp.seek(0,os.SEEK_END)
self.size = self.fp.tell()
self.fp.seek(0,os.SEEK_SET) def Search_Areacode(self,areacode,start_p = 0):
fp_start = start_p
fp_end = self.size while fp_start < fp_end:
mid = fp_start + (fp_end - fp_start)/2
self.fp.seek(mid,os.SEEK_SET) self.Search_LineHead() line = self.fp.readline()
val = self.Search_cmp(areacode[3][:9], line)
if val == 0:
ac,province,provider=line.split('|')
print "%s|%s|%s"%(province,areacode[3],areacode[4])
break
elif val == 1:
fp_start = self.fp.tell()
else:
fp_end = mid
#print areacode
def Search_cmp(self,areacode,line):
tmp = line.split('|')
return cmp(areacode,tmp[0]) def Search_LineHead(self):
while self.fp.tell() > 0:
self.fp.seek(-1,os.SEEK_CUR)
val = self.fp.read(1)
if val == '\n':
break
#print val
self.fp.seek(-1,os.SEEK_CUR)
def Search_DeInit(self):
self.fp.close() if __name__ == '__main__':
# 通过管道输入
log_line = sys.stdin.readlines()
obj = SearchAreacode('area_code.txt')
for line in log_line:
content = line.split(' ')
#print content[3][:9]
obj.Search_Areacode(content) obj.Search_DeInit()