ip_search.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from ip2Region import Ip2Region
  2. def ip_search(ip, region_type, algorithm='btree'):
  3. db_file = './ip2region.db'
  4. searcher = Ip2Region(dbfile=db_file)
  5. try:
  6. if algorithm == "binary":
  7. data = searcher.binarySearch(ip.strip())
  8. elif algorithm == "memory":
  9. data = searcher.memorySearch(ip.strip())
  10. else:
  11. data = searcher.btreeSearch(ip.strip())
  12. region = data['region'].decode('utf-8').split('|')
  13. if region_type == 'country':
  14. return region[0].strip()
  15. if region_type == 'province':
  16. return region[2].strip()
  17. if region_type == 'city':
  18. return region[3].strip()
  19. except Exception as e:
  20. # print(e)
  21. return None
  22. def region2code(region):
  23. code_file = './ip_code.txt'
  24. code_map = {}
  25. with open(code_file, 'r', encoding='utf-8') as rf:
  26. lines = rf.readlines()
  27. for line in lines:
  28. seg_list = line.split('|')
  29. code_map[seg_list[0].strip()] = seg_list[1].strip()
  30. # print(code_map)
  31. code = code_map.get(region, None)
  32. # print(code)
  33. return code
  34. if __name__ == '__main__':
  35. # ip = '101.105.35.57'
  36. # res = ip_search(ip=ip, region_type='city', algorithm='binary')
  37. # print(res)
  38. region2code('河北省')