python - Tweepy:流式传输 X 分钟的数据?

标签 python twitter tweepy

我正在使用 tweepy 对公开的推文流进行关键词数据挖掘。这非常简单,并且已在多个地方进行了描述:

http://runnable.com/Us9rrMiTWf9bAAW3/how-to-stream-data-from-twitter-with-tweepy-for-python

http://adilmoujahid.com/posts/2014/07/twitter-analytics/

直接从第二个链接复制代码:

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

#Variables that contains the user credentials to access Twitter API 
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"


#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):

    def on_data(self, data):
        print data
        return True

    def on_error(self, status):
        print status


if __name__ == '__main__':

    #This handles Twitter authetification and the connection to Twitter Streaming API
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)

    #This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
    stream.filter(track=['python', 'javascript', 'ruby'])

我想不通的是如何将这些数据流式传输到 python 变量中? 而不是将其打印到屏幕上...我在 ipython 笔记本上工作并想在流式传输一分钟左右后,在某个变量 foo 中捕获流。此外,如何让流超时?它以这种方式无限期地运行。

相关:

Using tweepy to access Twitter's Streaming API

最佳答案

是的,在帖子中,@Adil Moujahid 提到他的代码运行了 3 天。我改编了相同的代码并进行了初始测试,进行了以下调整:

a) 添加了位置过滤器以获取有限的推文,而不是包含关键字的通用推文。 参见 How to add a location filter to tweepy module . 从这里,您可以在上面的代码中创建一个中间变量,如下所示:

stream_all = Stream(auth, l)

假设我们,选择旧金山地区,我们可以添加:

stream_SFO = stream_all.filter(locations=[-122.75,36.8,-121.75,37.8])  

假设过滤位置的时间少于过滤关键字的时间。

(b) 然后你可以过滤关键字:

tweet_iter = stream_SFO.filter(track=['python', 'javascript', 'ruby']) 

(c) 然后您可以将其写入文件,如下所示:

with open('file_name.json', 'w') as f:
        json.dump(tweet_iter,f,indent=1)

这应该花费更少的时间。我碰巧想解决您今天发布的同一个问题。因此,我没有执行时间。

希望这对您有所帮助。

关于python - Tweepy:流式传输 X 分钟的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701962/

相关文章:

python - tweepy api.user_timeline : count limited to 200

python - 如何处理 argparse 中缺少的参数?

python - MongoEngine 中的子查询

python - 具有 ImageField 属性的 Django UpdateView

php如何使用oauth制作正确的twitter api curl

ios - iOS 设备上还没有 Twitter 帐户

python - 导入错误 : No module named 'tweepy.streaming' ; 'tweepy' is not a package

python - 如何在Finder中制作“右键单击选项”? (苹果电脑)

javascript - 我如何使用此 JavaScript 返回带有特定哈希标签的推文?

Python + Tweepy (STREAM API) - 解析某些值/对象的 JSON 输出