Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tweepy:X分钟的数据流?_Python_Twitter_Tweepy - Fatal编程技术网

Python Tweepy:X分钟的数据流?

Python Tweepy:X分钟的数据流?,python,twitter,tweepy,Python,Twitter,Tweepy,我正在使用tweepy对公共推文流中的关键词进行数据挖掘。这非常简单,在多个地方都有描述: 直接从第二个链接复制代码: #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 c

我正在使用tweepy对公共推文流中的关键词进行数据挖掘。这非常简单,在多个地方都有描述:

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

#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
中捕获流。此外,如何使流超时?它以这种方式无限期地运行

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

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

stream_all = Stream(auth, l)
with open('file_name.json', 'w') as f:
        json.dump(tweet_iter,f,indent=1)
假设我们选择旧金山地区,我们可以添加:

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) 然后,您可以将其写入文件,如下所示:

stream_all = Stream(auth, l)
with open('file_name.json', 'w') as f:
        json.dump(tweet_iter,f,indent=1)
这应该需要更少的时间。顺便提一下,我想回答你今天发布的同一个问题。因此,我没有执行时间


希望这能有所帮助。

我注意到您希望将数据流化到一个变量中以供以后使用。我这样做的方式是创建一个方法,使用sqlite3和sqlalchemy将数据流传输到数据库中

例如,这里首先是常规代码:

import tweepy
import json
import time
import db_commands
import credentials

API_KEY = credentials.ApiKey 
API_KEY_SECRET = credentials.ApiKeySecret
ACCESS_TOKEN = credentials.AccessToken
ACCESS_TOKEN_SECRET = credentials.AccessTokenSecret

def create_auth_instance():
    """Set up Authentication Instance"""
    auth = tweepy.OAuthHandler(API_KEY, API_KEY_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth, wait_on_rate_limit = True)

    return api

class MyStreamListener(tweepy.StreamListener):
    """ Listen for tweets """
    def __init__(self, api=None):
        self.counter = 0
        # References the auth instance for the listener
        self.api = create_auth_instance()
        # Creates a database command instance
        self.dbms = db_commands.MyDatabase(db_commands.SQLITE, dbname='mydb.sqlite')
        # Creates a database table
        self.dbms.create_db_tables()


    def on_connect(self):
        """Notify when user connected to twitter"""
        print("Connected to Twitter API!")


    def on_status(self, tweet):
        """
        Everytime a tweet is tracked, add the contents of the tweet,
        its username, text, and date created, into a sqlite3 database
        """         
        user = tweet.user.screen_name
        text = tweet.text
        date_created = tweet.created_at

        self.dbms.insert(user, text, date_created)


    def on_error(self, status_code):
        """Handle error codes"""
        if status_code == 420:
            # Return False if stream disconnects
            return False  

def main():
    """Create twitter listener (Stream)"""
    tracker_subject = input("Type subject to track: ")
    twitter_listener = MyStreamListener()
    myStream = tweepy.Stream(auth=twitter_listener.api.auth, listener=twitter_listener)
    myStream.filter(track=[tracker_subject], is_async=True)


main()
正如您在代码中看到的,我们验证并创建一个侦听器,然后激活一个流

twitter_listener = MyStreamListener()
myStream = tweepy.Stream(auth=twitter_listener.api.auth, listener=twitter_listener)
myStream.filter(track=[tracker_subject], is_async=True)
每次我们收到一条tweet,都会执行“on_status”功能,该功能可用于对正在传输的tweet数据执行一组操作

def on_status(self, tweet):
    """
    Everytime a tweet is tracked, add the contents of the tweet,
    its username, text, and date created, into a sqlite3 database
    """         
    user = tweet.user.screen_name
    text = tweet.text
    date_created = tweet.created_at

    self.dbms.insert(user, text, date_created)
Tweet数据Tweet由用户、文本、日期三个变量捕获,创建并引用MyStreamListener类的init函数中初始化的数据库控制器。此插入函数是从导入的db_命令文件中调用的

下面是位于db_commands.py文件中的代码,该文件使用import db_命令导入到代码中


这段代码使用sqlalchemy包创建sqlite3数据库并将tweets发布到tweets表。Sqlalchemy可以很容易地与pip安装Sqlalchemy一起安装。如果您同时使用这两个代码,您应该能够通过过滤器将tweet刮到数据库中。请让我知道这是否有帮助,如果您还有任何其他问题。

好的,让我来讨论一下。您是否在子流程中进行过流处理,以使其在运行时不会冻结程序3天?是的,我以前所做的是使用nohup运行python程序,如下所示:nohup python_file.py&exit请参见[.稍后,如果出现问题,如果您想终止进程,请尝试:ps-ef | grep nohup并使用该进程id终止以nohup启动的进程:例如:kill-9 1787 787请参见[您也可以使用MIT的Mosh,它本质上是一种在移动设备上工作的持久SSH。