Tweepy:传输数据 X 分钟?

2024-03-22

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

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

http://adilmoujahid.com/posts/2014/07/twitter-analytics/ 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直播一分钟左右后。此外,如何让流超时?它以这种方式无限期地运行。

Related:

使用 tweepy 访问 Twitter 的 Streaming API https://stackoverflow.com/questions/10970550/using-tweepy-to-access-twitters-streaming-api?rq=1


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

a) 添加了位置过滤器以获取有限的推文,而不是包含关键字的通用推文。 看如何向 tweepy 模块添加位置过滤器 https://stackoverflow.com/questions/22889122/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)

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

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tweepy:传输数据 X 分钟? 的相关文章

随机推荐