【问题标题】:How to iterate through a list containing Twitter Stream data?如何遍历包含 Twitter Stream 数据的列表?
【发布时间】:2018-10-06 14:58:04
【问题描述】:

我正在使用 tweepy Streaming api 从 twitter 流式传输数据,

class MyStreamListener(tweepy.StreamListener):
def __init__(self):
    super().__init__()
    self.counter = 0
    self.limit = 8
    self.q=list()

def on_status(self, status):
    self.counter += 1
    if self.counter < self.limit:
        self.q.append(status.user.name)
        self.q.append(status.user.statuses_count)
        #print(status.text)
    else:
        myStream.disconnect()
        print(self.q)

on_status 方法中,我已将所有数据和status_count 存储在列表中,但是当我尝试迭代数据时,我无法这样做

enter code here
tweet_list=list()
tweet_list.append(myStream.filter(track=[p]))
#tweet_list=myStream.filter(track=[p])
print(len(myStream.filter(track=[p])))

我得到这个结果:

['Chanchinthar', 1063, 'Sourabh', 4424]
Traceback (most recent call last):
File "C:/Users/TharunReddy/Desktop/pothi/twitter.py", line 51, in <module>
print(len(myStream.filter(track=[p])))
TypeError: object of type 'NoneType' has no len()

如何将推文存储在列表中并能够对其进行迭代? 有人请帮忙!

【问题讨论】:

    标签: python twitter tweepy twitter-streaming-api


    【解决方案1】:

    您的myStream 对象不是一个列表,而是一个生成器(它又是一种迭代器)。迭代器基本上是可迭代的(如列表),其元素一次计算(惰性)一个:只需要一次。这是一种内存效率更高的结构,但无法计算长度。 (此外,您还可以对它们进行一次迭代)。

    TLDR:将您的myStream 转换为列表:list(myStream),一切都会好起来的。

    有关生成器/迭代器的更多信息,请参阅here

    【讨论】:

      猜你喜欢
      • 2018-07-16
      • 2018-06-11
      • 2016-08-21
      • 2013-07-26
      • 2019-07-22
      • 2012-04-21
      • 2020-03-22
      • 1970-01-01
      • 2020-09-11
      相关资源
      最近更新 更多