
國產精品大模型API價格對比:通義千問 Max、字節跳動Doubao 1.5 pro 256k、DeepSeek V3
在開始之前,請確保您已設置好 Google Places API 并獲取了 API 密鑰。本文將使用 Place Search API 的“附近搜索”端點來實現功能。
首先,創建一個新文件,例如 [rest](http://m.dlbhg.com/provider/uid2024123057893a6ee1f4)aurants.py
,并導入以下所需的 Python 包:
import random
import geocoder
import requests
import json
import geopy.distance
# 獲取當前位置的經緯度
g = geocoder.ip('me')
currLocCoords = (g.latlng[0], g.latlng[1])
currLocCoordsURL = str(g.latlng[0]) + "%2C" + str(g.latlng[1])
# Google Places API 基礎 URL
my_api_key = "&key=YOUR_API_KEY"
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + currLocCoordsURL
如果您尚未安裝這些包,可以通過 pip install
命令安裝。
為了找到附近的餐館,我們需要構建一個包含參數的 API 請求 URL。以下代碼展示了如何根據用戶輸入動態生成 URL:
# 獲取用戶輸入的餐廳類型
[keyword](http://m.dlbhg.com/provider/uid2024121921342cbdf802) = input("What type of restaurant? (optional) ").lower().replace(" ", "%20")
if keyword != "":
keyword = "&keyword=" + keyword
else:
keyword = "&keyword=[food](http://m.dlbhg.com/provider/uid2024102319521f45d719)"
url = url + keyword
# 獲取用戶輸入的價格范圍
maxprice = input("Maximum $s, 0 to 4? (optional) ")
if maxprice != "":
maxprice = "&maxprice=" + maxprice
url = url + maxprice
# 獲取用戶是否要求餐廳當前營業
opennow = input("Does it have to be open now? (Y or N, optional) ").lower()
if opennow == "y":
opennow = "&opennow=true"
url = url + opennow
elif opennow == "n":
opennow = "&opennow=false"
url = url + opennow
# 獲取用戶輸入的搜索半徑
radius = input("Maximum distance willing to go in miles? (optional) ")
if radius != "":
radius = str(round(float(radius) * 1609.34))
# 轉換為米
radius = "&radius=" + radius
url = url + radius
else:
url = url + "&radius=3200"
# 默認半徑為3200米(約2英里)
通過以上代碼,用戶可以靈活設置搜索參數,包括餐廳類型、價格范圍、是否營業以及搜索半徑。
完成 URL 構建后,我們將發送 HTTP 請求并解析返回的 JSON 數據:
# 添加 API 密鑰并發送請求
url = url + my_api_key
response = requests.request("GET", url)
# 解析 JSON 響應
response = json.loads(response.text)
status = response['status']
if status == "OK":
results = response["results"]
else:
print(status)
exit()
status
字段用于檢查請求是否成功,例如返回 "OK" 表示成功,而 "ZERO_RESULTS" 表示沒有找到結果。
為了更方便地處理返回的餐廳數據,我們定義了一個 restaurant
類,用于存儲餐廳的關鍵信息:
class restaurant:
def __init__(self):
self.name = ""
self.businessStatus = ""
self.openNow = False
self.priceLevel = ""
self.rating = -1
self.totalUserRatings = -1
self.distance = -1
self.address = ""
以下代碼通過循環處理返回的 JSON 數據,并提取關鍵信息存儲到 restaurant
對象中:
numPlaces = len(results)
restAttributesList = ["name", "businessStatus", "openNow", "priceLevel", "rating", "totalUserRatings", "distance", "address"]
restInstVarList = []
for i in range(numPlaces):
currPlace = results[i]
rest = restaurant()
try:
rest.name = currPlace["name"]
except KeyError:
pass
try:
rest.businessStatus = currPlace["business_status"]
except KeyError:
pass
try:
rest.openNow = currPlace["opening_hours"]["open_now"]
except KeyError:
pass
try:
rest.priceLevel = currPlace["price_level"]
except KeyError:
pass
try:
rest.rating = currPlace["rating"]
except KeyError:
pass
try:
rest.totalUserRatings = currPlace["user_ratings_total"]
except KeyError:
pass
try:
placeCoords = currPlace["geometry"]["location"]
currPlaceCoords = (placeCoords["lat"], placeCoords["lng"])
rest.distance = geopy.distance.geodesic(currLocCoords, currPlaceCoords).miles
except KeyError:
pass
try:
rest.address = currPlace["vicinity"]
except KeyError:
pass
restInstVarList.append(vars(rest))
通過 try-except
塊,我們可以安全地處理缺失字段,避免程序因 KeyError 中斷。
以下代碼用于打印所有餐廳的信息:
for r in restInstVarList:
print(r["name"] + ": ")
for i in range(1, 8):
a = restAttributesList[i]
print("t" + a + ": " + str(r[a]))
print("n")
如果希望隨機選擇一家餐廳,可以使用以下代碼:
import random
randomChoice = random.choice(restInstVarList)
print(randomChoice["name"] + ": ")
for i in range(1, 8):
a = restAttributesList[i]
print("t" + a + ": " + str(randomChoice[a]))
通過本文的教程,您可以使用 Google Places API 構建一個簡單的餐廳選擇程序。這個項目不僅能解決實際問題,還能幫助您學習和實踐 API 調用、數據處理等編程技能。如果您有任何問題或建議,歡迎留言交流。
原文鏈接: https://medium.com/@nagasameer/building-a-restaurant-picker-program-using-google-places-api-99aa3108310
國產精品大模型API價格對比:通義千問 Max、字節跳動Doubao 1.5 pro 256k、DeepSeek V3
REST API:關鍵概念、最佳實踐和優勢
大模型API亂斗,基礎參數、核心性能:Grok3、deepseek R1、ChatGPT 4o
3大AI語言大模型API價格的區別:ChatGPT 4o、百度千帆 ERNIE 4.0、阿里通義千問 Max
從頭開始構建 GPT 風格的 LLM 分類器
3大AI語言大模型API基礎參數、核心性能的區別:ChatGPT 4o、百度千帆 ERNIE 4.0、阿里通義千問 Max
大模型API亂斗,價格對比:Grok3、deepseek R1、ChatGPT 4o
一步步教你進行 Python REST API 身份驗證
FastAPI 異步編程:提升 API 性能