python - 使用 Tweepy (4.10.0) Tweet_id 获取推文回复

标签 python dataframe twitter tweepy

我正在尝试使用 Tweepy python 包来获取对推文的实际回复。我分解了迄今为止我所做的工作流程:

我导入模块并使用 tweepy 配置身份验证变量:

client = tweepy.Client(bearer_token=bearer_token, wait_on_rate_limit=True)
covid_tweets = []

for mytweets in tweepy.Paginator(client.search_all_tweets, query = '#COVID lang:en', 
  user_fields=['username', 'public_metrics', 'description', 'location'], tweet_fields 
  = ['created_at', 'geo', 'public_metrics', 'text'], expansions = 'author_id', 
  start_time = '2019-12-30T00:00:00Z', end_time = '2020-01-15T00:00:00Z', 
  max_results=10):
  time.sleep(2)
  covid_tweets.append(mytweets)

然后,我使用 for 循环搜索我想要的主题标签和 Tweepy Paginator 的参数,并附加到一个空列表:

client = tweepy.Client(bearer_token=bearer_token, wait_on_rate_limit=True)
covid_tweets = []

for mytweets in tweepy.Paginator(client.search_all_tweets, query = '#COVID lang:en', 
 user_fields=['username', 'public_metrics', 'description', 'location'], tweet_fields 
 = ['created_at', 'geo', 'public_metrics', 'text'], expansions = 'author_id', 
 start_time = '2019-12-30T00:00:00Z', end_time = '2020-01-15T00:00:00Z', 
 max_results=10):
    time.sleep(2)
    covid_tweets.append(mytweets)

然后我通过提取某些关键字段[用户字典,user_object]将此列表转换为数据帧:

#Convert Covid-19 tweets to a DF
result = []
user_dict = {}

# Loop through each response object
for response in covid_tweets:

 for user in response.includes['users']:
   user_dict[user.id] = {'username': user.username,
                          'followers': user.public_metrics['followers_count'],
                          'tweets': user.public_metrics['tweet_count'],
                          'description': user.description,
                          'location': user.location
                         }
 for tweet in response.data:
   # For each tweet, find the author's information
   author_info = user_dict[tweet.author_id]
   #check for condition
   if ('RT @' not in tweet.text):
 # Put all information we want to keep in a single dictionary for each tweet
 result.append({'author_id': tweet.author_id,
                       'tweet_id': tweet.id,
                       'username': author_info['username'],
                       'author_followers': author_info['followers'],
                       'author_tweets': author_info['tweets'],
                       'author_description': author_info['description'],
                       'author_location': author_info['location'],
                       'text': tweet.text,
                       'created_at': tweet.created_at,
                       'retweets': tweet.public_metrics['retweet_count'],
                       'replies': tweet.public_metrics['reply_count'],
                       'likes': tweet.public_metrics['like_count'],
                       'quote_count': tweet.public_metrics['quote_count']
                      })

 # Change this list of dictionaries into a dataframe
 df_1 = pd.DataFrame(result)
  • 现在我的问题是,从数据帧中,我可以看到推文和推文的回复计数,图像的证明如下所示: enter image description here
  • 我检查了如何从推文中获取回复。所以我做了一些检查,并想遵循这个代码流函数:

    def get_all_replies(tweet, api, fout, depth=10, Verbose=False):
    global rep
    if depth < 1:
        if Verbose:
            print('Max depth reached')
        return
    user = tweet.user.screen_name
    tweet_id = tweet.id
    search_query = '@' + user
    
    # filter out retweets
    retweet_filter = '-filter:retweets'
    
    query = search_query + retweet_filter
    try:
        myCursor = tweepy.Cursor(api.search_tweets, q=query,
                                 since_id=tweet_id,
                                 max_id=None,
                                 tweet_mode='extended').items()
        rep = [reply for reply in myCursor if reply.in_reply_to_status_id == tweet_id]
    except tweepy.TweepyException as e:
        sys.stderr.write(('Error get_all_replies: {}\n').format(e))
        time.sleep(60)
    
    if len(rep) != 0:
        if Verbose:
            if hasattr(tweet, 'full_text'):
                print('Saving replies to: %s' % tweet.full_text)
            elif hasattr(tweet, 'text'):
                print('Saving replies to: %s' % tweet.text)
            print("Output path: %s" % fout)
    
        # save to file
        with open(fout, 'a+') as (f):
            for reply in rep:
                data_to_file = json.dumps(reply._json)
                f.write(data_to_file + '\n')
    
            # recursive call
            get_all_replies(reply, api, fout, depth=depth - 1, Verbose=False)
    
    return
    

    基本上,通过这个函数,我循环遍历数据帧并为推文选择“tweet_id”和“the screen_name”,然后设计一个搜索查询,但我意识到在“rep”列表部分返回一个空列表并逐行调试,实际上表明 in_reply_to_status_id 与 tweet_id 不同,并且即使数据帧的回复计数显示非零,也是空列表的原因。

    我知道这很长,但我真的想展示我到目前为止所做的事情并解释每个过程。谢谢 注意:我可以访问学术研究 API

    最佳答案

    好吧,对于每个试图解决这个障碍的人来说,我终于找到了一种获得推文回复的方法。在我的用例中,我有 Twitter 的学术研究 API。 geduldig在他的github上提供的代码 Github终于解决了我的 稍微调整一下的问题。需要注意的是,使用 TwitterAPI 包,如果忽略“start_time”或“end_time”参数,您可能只会获得父推文,因此结构如下:

    pager = TwitterPager(api, 'tweets/search/all',
        {
            'query':f'conversation_id:{CONVERSATION_ID}',
            'start_time': '2019-12-30T00:00:00Z',
            'end_time': '2021-12-31T00:00:00Z',
            'expansions':'author_id',
            'tweet.fields':'author_id,conversation_id,created_at,referenced_tweets'
        },
        hydrate_type=HydrateType.REPLACE)
    

    我希望这对社区有帮助。谢谢。

    关于python - 使用 Tweepy (4.10.0) Tweet_id 获取推文回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73094264/

    相关文章:

    html - Twitter 卡片图像模糊

    r - 根据列中连续值形成的模式从数据框中选择行

    python - 如何使用多个 bool 条件选择 Pandas DataFrame 中的特定列

    python - 在 python 中,为什么没有换行符就无法打印

    python - 导入错误 : No module named responses

    python - 如何计算pandas数据框中 "better"比其他点有多少个?

    python - 使用 requests 和 concurrent.futures 异步发送多个 API post 请求

    html - 如何调整线条的线宽?

    python - 自定义 Flask-JWT 验证功能

    python - 用 Python 计算分子化合物中的元素数量(如果可能的话递归)?