【问题标题】:How to iterate through a list containing search queries using a for loop如何使用 for 循环遍历包含搜索查询的列表
【发布时间】:2022-01-27 03:00:33
【问题描述】:

我正在尝试遍历包含不同搜索查询的列表。列表“search_query_list”中的每个元素都区分政治家的姓名和 Twitter 用户名。

search_query_list = 
['(block me OR blocked me) -vote -$2000 -Senate -House -is:retweet lang:en (SenJonKyl OR Jon Kyl)', 
'(block me OR blocked me) -vote -$2000 -Senate -House -is:retweet lang:en (DougJones OR Doug Jones)', 
'(block me OR blocked me) -vote -$2000 -Senate -House -is:retweet lang:en (timkaine OR Tim Kaine)']

我正在尝试遍历列表中的每个元素,并使用 for 循环为每个政治家提取推文。但是,由于某些未知原因,代码没有提取任何推文?

pol_tweets = [] # Empty list

def getTweets():
    client = getClient()
    for x in searh_query:
        tweets = client.search_all_tweets(query=x,
                                          tweet_fields=['created_at', 'author_id'],
                                          start_time='2017-01-01T00:00:00Z',
                                          max_results=30,
                                          expansions=['attachments.media_keys', 'author_id'],
                                          media_fields=['preview_image_url', 'url'],
                                          user_fields=['description'])

        return pol_tweets.append(tweets) # Append tweets to empty list

results = getTweets()

输出

print(results)
None

【问题讨论】:

  • 你可以添加预期的输出,它有点令人困惑 - client = getClient(): 和 client.search_all_tweets()

标签: python for-loop append tweepy


【解决方案1】:

我不完全知道其他被调用的函数是做什么的,但你对每个结果都有一个返回语句。

请尝试

def getTweets():
client = getClient()
pol_tweets = []
for x in search_query:
    tweets = client.search_all_tweets(query=x,
                                      tweet_fields=['created_at', 'author_id'],
                                      start_time='2017-01-01T00:00:00Z',
                                      max_results=30,
                                      expansions=['attachments.media_keys', 'author_id'],
                                      media_fields=['preview_image_url', 'url'],
                                      user_fields=['description'])

    pol_tweets.append(tweets) # Append tweets to empty list
return pol_tweets

打印(getTweets())

如您所见,我在函数 getTweets 中定义了空数组,并将项目附加到您的 for 循环中的列表中。

在所有迭代完成后,我返回完成的数组。 使用虚拟数据,这对我有用。

【讨论】:

  • 嗨斯特凡。感谢您的回复。使用您的代码时,我只为 search_query_list 中的第一个政治家(即 Jon Kyle)提取推文。我已将 max_result 增加到 500,所以这不是因为我在迭代到列表中的下一个政治家之前达到了提取推文的限制。
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多