📜  Python – Tweepy 中的 API.reverse_geocode()

📅  最后修改于: 2022-05-13 01:54:53.009000             🧑  作者: Mango

Python – Tweepy 中的 API.reverse_geocode()

Twitter是一个流行的社交网络,用户在其中分享称为推文的消息。 Twitter 允许我们使用 Twitter API 或Tweepy挖掘任何用户的数据。数据将是从用户那里提取的推文。首先要做的是从 Twitter 开发人员那里轻松获得每个用户可用的消费者密钥、消费者秘密、访问密钥和访问秘密。这些密钥将帮助 API 进行身份验证。

API.reverse_geocode()

Tweepy 模块中API类的reverse_geocode()方法用于获取所提供坐标的附近位置。

示例 1:

# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# the coordinates
lat = 28
long = 77
  
# fetching the locations
locations = api.reverse_geocode(lat, long)
  
print(str(len(locations)) + " location(s) is / are fetched.")
print("\nThe location(s) is / are :")
for location in locations:
    print(location.name)

输出 :

2 location(s) is/are fetched.

The location(s) is/are :
Haryana
India

示例 2:给出无效坐标时引发异常。

# invalid coordinates
lat = 200
long = 123
  
# fetching the locations
locations = api.reverse_geocode(lat, long)

输出 :

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\tweepytesting.py", line 28, in 
    locations = api.reverse_geocode(lat, long)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 250, in _call
    return method.execute()
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 236, in execute
    result = self.parser.parse(self, resp.text)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\parsers.py", line 98, in parse
    result = model.parse_list(method.api, json)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\models.py", line 481, in parse_list
    item_list = json_list['result']['places']
KeyError: 'result'