【问题标题】:Python list is empty which shouldn't be emptyPython列表为空,不应为空
【发布时间】:2020-12-24 16:11:46
【问题描述】:

我在这里复制示例:https://www.earthdatascience.org/courses/use-data-open-source-python/intro-to-apis/twitter-data-in-python/

一切顺利。只是,我想将命令应用于示例中的列表。

test = [tweet.text for tweet in tweets]

但它本质上返回一个空列表:print(test)。

编辑:

MWE:

import sys
sys.modules[__name__].__dict__.clear()

import os
import tweepy as tw
import pandas as pd

consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'


auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)




# Define the search term and the date_since date as variables
search_words = "#wildfire"
date_since = "2020-01-09"

#Collect tweets

tweets = tw.Cursor(api.search,
    q=search_words,
    lang = "ger",
    since=date_since).items(5)




new_search = search_words + " -filter:retweets"
#new_search


tweets = tw.Cursor(api.search,
                       q=new_search,
                       lang="en",
                       since=date_since).items(5)

for tweet in tweets:
       print(tweet.text)
test = [tweet.text for tweet in tweets]
print(test)

一些 cmets 建议推文可能是空的。如果我没记错的话,tweeps 不是空的,因为我可以遍历内容。

我想这很容易,但我们将不胜感激。

谢谢

丹尼尔

【问题讨论】:

  • 该列表为空当且仅当tweets 为空。
  • 在您的代码中,tweets 必须为空,因此 test 也最终为空。
  • 请出示完整代码的minimal reproducible example
  • 我不知道Cursor.items返回什么样的东西,但很可能它是空的,或者它只能迭代一次(你试图迭代它两次)。
  • 确实只能迭代一次。

标签: python list tweepy


【解决方案1】:

Cursor.items returns an iterator。你在这里迭代它:

for tweet in tweets:
   print(tweet.text)

让它筋疲力尽。然后你尝试再次迭代它

test = [tweet.text for tweet in tweets]

但它没有剩余物品。

首先制作列表,然后您就可以将数据保存在一个可以迭代任意多次的表单中。

test = [tweet.text for tweet in tweets]
for text in test:
    print(text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2016-05-22
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多