I am trying to write code to print the country code of all tweets that match a search query. I have tried to follow tweepy examples as well as twitter’s documentation and examples on the internet, but I have not been able to find the way to do it. I have academic research access to the API, and this is my code (the query is a toy example):
import tweepy
bt = "..."
client = tweepy.Client(bearer_token=bt)
query = 'hello has:geo -is:retweet'
response = client.search_all_tweets(query=query, tweet_fields=['geo'], place_fields=['country_code'],
expansions=['geo.place_id'], max_results=10)
tweets = response.data
includes = response.includes
places = includes["places"]
places = {p["id"]: p for p in places}
for tweet in tweets:
print(tweet.id)
print(tweet.text)
print(" country: ", tweet.country_code)
I get the following error:
line 67, in <module>
print(" country: ", tweet.country_code)
File "mypath", line 35, in __getattr__
raise AttributeError from None
AttributeError
I have tried adding this if
statement I found in another question:
if tweet.place is not None:
print(" country: ",tweet.country_code)
else:
print("Place not found")
But it raises the same error, but this time on the if
statement line. I have tried printing the tweet.geo
field but all it does is print the place id, which is not what I want.
I have seen many responses about how to filter by country. But this is for a linguistics research on the use of specifc structures around the world, so I need to get all of its uses and information on the country where the tweet was posted from.
How can I get the country code?
2
Answers
I manage to find a solution tanks to @mkrieger1 's help.
This solution does still yield tweets for which the country information is not set. The filter is applied in the
for
loop.According to https://docs.tweepy.org/en/stable/v2_models.html,
country_code
is not an attribute of aTweet
object, but of aPlace
object.Tweet
objects can have aplace
attribute, I presume it will be aPlace
instance as "child object".So you would have to use
tweet.place.country_code
.The
if
statement you mentioned hints at this but maybe you misinterpreted what you found.It should be
so that you first check if
tweet.place
exists, and only then access thecountry_code
attribute oftweet.place
(not oftweet
).