python 利用高德得到地址對應的經偉度,由於地址原因在指定時間範圍內得不到經偉度而終止,pandas讀寫

myrj發表於2024-08-16
import requests,sys
import json,math,xlrd,xlwt,time
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import sin, asin, cos, radians, fabs, sqrt
import pandas as pd
from geopy.distance import geodesic
from openpyxl import load_workbook
import re
 
def search_chinese_address(text):
    # 正規表示式模式,匹配常見的中文地址
    pattern = r'[\u4e00-\u9fa5]{2,}.*[\u4e00-\u9fa5]{2,}'
    matches = re.findall(pattern, text)
    return matches
def search_chinese_address(text):
    # 正規表示式模式,匹配常見的中文地址
    pattern = r'[\u4e00-\u9fa5]+區站}'
    matches = re.findall(pattern, text)
    return matches
 
# 使用函式
##addresses = find_addresses(text)
##for address in addresses:
##    print(address)
    
def dzjws(dizhii):
    url = 'https://restapi.amap.com/v3/geocode/geo'   
    # 將兩個引數放入字典
    params = { 'key': '1a586e7b6da8bee4af4944bc6c3abbe9',
           'address': dizhii }
    a=0
    st1=time.time()
    tt=10
    while a==0:
        st2=time.time()
        if st2-st1>12:
            dzhi=""
            break
        try:
            res = requests.get(url, params,timeout=5)
            jd = json.loads(res.text)
            #dzhi=jd['geocodes'][0]['location']
            dzhi=jd['geocodes'][0]['location']
            a=1
        except:
            a=0
    return dzhi
##wb=load_workbook('jieguo1.xlsx')
index=-1
df=pd.read_excel('jieguo1.xlsx')
##df["jwd"]=""
##df["xx"]=""
##
##for xx in zip(df["dizhi1"]):
##    
##    index=index+1
##    dizhi=str(xx[0])
##    didi=search_chinese_address(dizhi)
##    for address in didi:
##        print(dizhi,address)
##
##sys.exit(0)

    
for xx in zip(df["dizhi"]):
    
    index=index+1
    dizhi=str(xx[0])
    print(dizhi)
    st1=time.time()
    tt=10
    xx=0
    mm=""
    while 1:
        st2=time.time()
        if st2-st1>tt:
            xx=1
            break
        mm=dzjws(dizhi)
        if mm!="":
            break
    if xx==1:
        mm=""
    print(dizhi,mm)
    df.loc[index,"jwd"]=mm
    #time.sleep(2)
    #break
##df["jwd"]=df["dizhi"].apply(dzjws)
df.to_excel("jieguo5x.xlsx",index=False)

python 利用高德得到地址對應的經偉度,由於地址原因在指定時間範圍內得不到經偉度而終止,pandas讀寫

相關文章