Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
API.reverse_geocode()
The reverse_geocode()
method of the API
class in Tweepy module is used to fetches the nearby locations for the provided coordinates.
Syntax : API.reverse_geocode(lat, long, accuracy, granularity, max_results)
Parameters :
- lat : latitude of the location.
- long : longitude of the location.
- accuracy : Specify the “region” in which to search.
- granularity : Assumed to be neighborhood by default, can also be city..
- max_results : maximum number of results to fetch.
Returns : a list of objects of class Place
Example 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) |
Output :
2 location(s) is/are fetched. The location(s) is/are : Haryana India
Example 2 : Exception is raised when giving invalid coordinates.
# invalid coordinates lat = 200 long = 123 # fetching the locations locations = api.reverse_geocode(lat, long ) |
Output :
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'
<!–
–>
Please Login to comment…