I am getting the tweets and the corresponding id of that user in an object obj
. I want to append the object to a table but I get an empty table. What's the problem, please?
tweet_tab = []
def searchTweets(client):
for i in users_name:
client = getClient()
user = client.get_user(username=i)
userId = user.data.id
tweets = client.get_users_tweets(userId,
expansions=[
'author_id', 'referenced_tweets.id', 'referenced_tweets.id.author_id',
'in_reply_to_user_id', 'attachments.media_keys', 'entities.mentions.username', 'geo.place_id'],
tweet_fields=[
'id', 'text', 'author_id', 'created_at', 'conversation_id', 'entities',
'public_metrics', 'referenced_tweets'
],
user_fields=[
'id', 'name', 'username', 'created_at', 'description', 'public_metrics',
'verified'
],
place_fields=['full_name', 'id'],
media_fields=['type', 'url', 'alt_text', 'public_metrics'])
if not tweets is None and len(tweets) > 0:
obj = {}
obj['id'] = userId
obj['text'] = tweets
tweet_tab.append(obj)
return tweet_tab
print("tableau final", tweet_tab)
CodePudding user response:
Problem looks like it's already solved, as Michael pointed out it's missplaced return
statement but I would like to give you one hint that can help you eluding such problems in future. Good programming habits say that (if possible) body of loop should be in different function. That way we won't have a problem with bad placed return, look:
def searchTweet(username):
client = getClient()
user = client.get_user(username=username)
userId = user.data.id
tweets = client.get_users_tweets(...)
if not tweets: # it works because empty list evaluates to False
return None
return {"id": userId, "text": tweets}
def searchTweets():
tweet_tab = []
for i in users_name:
res = searchTweet(username=i)
if res is not None:
tweet_tab.append(res)
return tweet_tab
Or even with python list comprehesion
def searchTweets():
res = [searchTweet(username) for username in users_name]
return [el for el in res if el is not None]
With using of cache decorator you can call this function many times to get that list which will be calculated only once.
from functools import cache
@cache
def searchTweets():
res = [searchTweet(username) for username in users_name]
return [el for el in res if el is not None]
CodePudding user response:
I think you should change
if not tweets is None and len(tweets) > 0
to
if tweets is not None and len(tweets) > 0
or
if tweets and len(tweets) > 0