2

我有一个文件,它从 python 中的 twitter 中提取信息并将状态消息运行到我的 shell 中。我想将它们从外壳中取出并放入数据库中。我不知道该怎么做。我也没有为它制作的数据库,我将在数据库堆栈上对此提出质疑。我的代码如下:

import time
import MySQLdb
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

# Go to http://dev.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key=" # Omitted "
consumer_secret=" # Omitted "

# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token=" # Omitted"
access_token_secret=" #Omitted "

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# If the authentication was successful, you should
# see the name of the account print out
print api.me().name

class StdOutListener(StreamListener):
        """ A listener handles tweets are the received from the stream.
        This is a basic listener that just prints received tweets to stdout.
        """
        def on_data(self, data):
            print data
            return True

        def on_error(self, status):
            print status

if __name__ == '__main__':
        l = StdOutListener()

        stream = Stream(auth, l)    
        stream.filter(track=['search term'])

如何从流中获取信息到数据库中?我还想过滤流以只允许某些信息进入。我想进入数据库的唯一信息如下:

  1. 留言作者
  2. 信息
  3. 日期/时间戳
  4. GEO(如果有)
  5. 来源 ie Tweetdeck, web, mobile yaddda yadda
  6. 消息是 RT'd
4

1 回答 1

1

这个问题需要很多信息,所以我只想给你一个概述,你需要什么......

首先,在 SO 和互联网上都有这种确切方法的例子。这是本教程中的粘贴示例

class StreamListener(tweepy.StreamListener):

    status_wrapper = TextWrapper(width=60, initial_indent='    ', 
                                    subsequent_indent='    ')
    conn = mdb.connect('localhost', 'dbUser','dbPass','dbBase')

    def on_status(self, status):
        try:
            cursor = self.conn.cursor()
            cursor.execute('INSERT INTO tweets (text, date) VALUES (%s, NOW())' ,(status.text))
            print self.status_wrapper.fill(status.text)
            print '\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source)
        except Exception, e:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            pass

此示例使用不同的数据库驱动程序。但是您将使用on_status处理程序来接收新数据,并将其拆分为值。然后你创建一个 sql INSERT 把它放到你的数据库中。

这是这个SO question中的一个 sqlite3 示例:

cur.execute("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, 
                                               status.author.screen_name, 
                                               status.created_at, 
                                               status.source))

这两个示例都要求您使用数据库客户端进行连接,然后获取一个游标(这是一个进行查询并让您查看结果的对象)。您可以查看有关 MySQLdb 的教程,以获得有关如何设置所有内容和进行查询的很好的概述。

如果您最终遇到了更集中的问题,那么可以单独解决。

于 2012-08-04T03:01:26.527 回答