首页 > 解决方案 > 如何使用for循环从DataFrame迭代所有推文的ID并将推文添加到DataFrame的空列

问题描述

我有一个 DataFrame,其中包含 twitter 的推文 ID 和情绪,我将使用它们进行情绪分析。数据框

我想使用“tweepy library”搜索所有 tweet_id 的推文,并将它们同时添加到这个 DataFrame 中。注意:我使用 try-except 因为很少有推文是私有的或已删除的,因此在抓取成千上万条推文时不会引发错误。

#Code:
# 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)

#Below for loop does not work. Maybe its not passing each tweet_id to the status=api.get_status()
#This tweepy code is correct. because i have tried this with list (by converting df's tweet_id #into list and then iterating those list to get status of each tweets but by using df it doesnt #work.
for index, row in df.iterrows():
  try:
    status = api.get_status(row['tweet_id'])
  except tweepy.TweepError:
    text = status.text
    df['tweets'].append(text)

标签: pythonpandasdataframefor-looptweepy

解决方案


推荐阅读