Python:分割URL的一部分以便在函数中使用

2024-10-04 05:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道已经有很多答案了,所以要处理splitpython的URL。但是,我想拆分一个URL,然后在函数中使用它

我在python中使用了一个curl请求:

r = requests.get('http://www.datasciencetoolkit.org/twofishes?query=New%York')
r.json()

它提供了以下内容:

{'interpretations': [{'what': '',
  'where': 'new york',
  'feature': {'cc': 'US',
    'geometry': {'center': {'lat': 40.742185, 'lng': -73.992602},
     ......
     # (lots more, but not needed here)

我想能够给任何城市/地点打电话,我想把latlng分开。例如,我想调用一个可以输入任何城市的函数,它用经纬度来响应。有点像this question(使用R)

这是我的尝试:

import requests

def lat_long(city):
    geocode_result = requests.get('http://www.datasciencetoolkit.org/twofishes?query= "city"')

我如何解析它,这样我就可以调用一个城市的函数


Tags: 函数答案orghttpurlcitygetwww
2条回答

以你的例子,我建议使用正则表达式和字符串插值。这个答案假设API每次都以相同的方式返回数据

import re, requests

def lat_long(city: str) -> tuple:
    # replace spaces with escapes
    city = re.sub('\s', '%20', city)
    res = requests.get(f'http://www.datasciencetoolkit.org/twofishes?query={city}')

    data = res.json()
    geo = data['interpretations'][0]['feature']['geometry']['center']

    return (geo['lat'], geo['lng'])

您可以在这个列表上循环查找城市名称,并在找到正确的城市时返回坐标

def lat_long(city):
    geocode_result = requests.get('http://www.datasciencetoolkit.org/twofishes?query= "city"')
    for interpretation in geocode_result["interpretations"]:
        if interpretation["where"] == city:
            return interpretation["feature"]["geometry"]["center"]

相关问题 更多 >