지번 주소 -> latitude, longitude 추출

ewillwin·2023년 1월 17일
0

TSMtech Record

목록 보기
29/39
  • 행정동코드 is False인 경우, 지번 주소를 통해 위도경도 추출
  • 얻은 위도와 경도를 통해 행정동코드를 얻을 예정
from urllib.request import urlopen
import requests as rq
from bs4 import BeautifulSoup as bs
from typing import final
from venv import create
import pandas as pd
from multiprocessing import Process
from typing import final
from venv import create
import requests
from decimal import Decimal
import re
import xml.etree.ElementTree as ET
import time
import json
import datetime
import sys
import googlemaps


def get_kaptCode():
    url = "http://apis.data.go.kr/1613000/AptListService2/getTotalAptList"
    serviceKey = ""
    serviceKey = requests.utils.unquote(serviceKey)
    params = {'serviceKey': serviceKey, 'numOfRows': 18987}
    response = requests.get(url, params=params)
    return response.text

def get_energy(reqDate, kaptCode):
    url = "http://apis.data.go.kr/1611000/ApHusEnergyUseInfoOfferService/getHsmpApHusUsgQtyInfoSearch"
    serviceKey = ""
    serviceKey = requests.utils.unquote(serviceKey)
    params = {'serviceKey': serviceKey, 'kaptCode': kaptCode, 'reqDate': reqDate}
    while(True):
        try:
            response = requests.get(url, params=params)
            if response.status_code == 200:
                break
        except:
            time.sleep(2)
            response = requests.get(url, params=params)
            if response.status_code == 200:
                break
    return response.text

def energy_parsing(energy_type, response):
    pattern = "<"+energy_type+">"+"(-?[0-9]+)</"+energy_type+">"
    result = re.findall(pattern, response)
    return result


googlemaps_key = ""
gmaps = googlemaps.Client(key=googlemaps_key)

addr = open("C:/Users/TSM/OneDrive/바탕 화면/alladdr/allfalse.csv", "r", encoding="cp949")
result = open("C:/Users/TSM/OneDrive/바탕 화면/alladdr/latlng.csv", "a", encoding="cp949")
start = 3927 # restart!
cnt = 0
for line in addr:
    if cnt == start:
        start += 1
        line_list = line.split(',')
        geo_location = gmaps.geocode(line_list[0])
        if not geo_location:
            tmp = line_list[0] + ',' + line_list[1] + ',' + "False" + ',' + "False" + '\n'
            result.write(tmp)
        else:
            geo_location = geo_location[0].get('geometry')
            print(geo_location)
            lat = geo_location['location']['lat']
            lng = geo_location['location']['lng']
            tmp = line_list[0] + ',' + line_list[1] + ',' + str(lat) + ',' + str(lng) + '\n'
            result.write(tmp)
    cnt += 1
addr.close()
result.close()
  • googlemaps API를 이용함
>>> pip install googlemaps
---------------------------
import googlemaps

-> service key를 발급 받을 때, 카드 등록을 해야하는데 사용 시작 시점으로부터 90일 까지 300$ 크레딧을 제공해주는듯. 그 후에 이용할 경우 요금이 부과될 수 있음

  • addr는 행정동코드가 false값을 가진 모든 지번주소를 모아둔 text file의 file descriptor인데, 중간에 오류가 발생할 경우 start, cnt 변수를 이용하여 그 이후부터 작동할 수 있게끔 구현함
  • geocode()로 해당 지번 주소의 위도, 경도를 얻을 수 없을 경우에는 일단 lat=False, lng=False 값을 넣어둠
  • line by line으로 처리하여 alladdr directory의 latlng.csv file에 append함
profile
Software Engineer @ LG Electronics

0개의 댓글