我正在一個物件中獲取該用戶的推文和相應的 id obj。我想將物件附加到一個表,但我得到一個空表。請問有什么問題嗎?
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)
uj5u.com熱心網友回復:
問題看起來已經解決了,正如邁克爾指出的那樣,這是錯誤的return陳述,但我想給你一個提示,可以幫助你在未來避免此類問題。良好的編程習慣說(如果可能)回圈體應該在不同的函式中。這樣我們就不會有錯誤放置回傳的問題,看看:
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
甚至使用 python 串列理解
def searchTweets():
res = [searchTweet(username) for username in users_name]
return [el for el in res if el is not None]
通過使用快取裝飾器,您可以多次呼叫此函式以獲取僅計算一次的串列。
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]
uj5u.com熱心網友回復:
我認為你應該
if not tweets is None and len(tweets) > 0改為
if tweets is not None and len(tweets) > 0 或者
if tweets and len(tweets) > 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/388956.html
上一篇:“AttributeError:'str'物件沒有屬性'descendants'錯誤,自動抓取bs4和selenium
下一篇:使用條件從二維串列中獲取特定元素
