使用Tweepy将推文插入MySQL数据库

时间:2015-06-18 23:32:35

标签: python mysql twitter

我正在尝试使用以下Python代码将已解析的推文插入到MySQL数据库中:

    #-*- coding: utf-8 -*-

    __author__ = 'sagars'

    import pymysql
    import tweepy
    import time
    import json
    from tweepy import Stream
    from tweepy import OAuthHandler
    from tweepy.streaming import StreamListener



class listener(StreamListener):

 def on_data(self, data):
        all_data = json.loads(data)
        tweet = all_data["text"]
        username = all_data["user"]["screen_name"]

        c.execute("INSERT INTO tweets (tweet_time, username, tweet) VALUES (%s,%s,%s)"
                  (time.time(), username, tweet))
        print (username, tweet)
        return True

def on_error(self, status):
    print (status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track = ["LeBron James"])

但是我遇到了以下错误:

Traceback (most recent call last):
  File "C:/Users/sagars/PycharmProjects/YouTube NLP Lessons/Twitter Stream to DB.py", line 45, in <module>
    twitterStream.filter(track = ["LeBron James"])
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 428, in filter
    self._start(async)
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 346, in _start
    self._run()
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 286, in _run
    raise exception
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 255, in _run
    self._read_loop(resp)
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 309, in _read_loop
    self._data(next_status_obj)
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 289, in _data
    if self.listener.on_data(data) is False:
  File "C:/Users/sagars/PycharmProjects/YouTube NLP Lessons/Twitter Stream to DB.py", line 35, in on_data
    (time.time(), username, tweet))
TypeError: 'str' object is not callable

如何调整代码以避免错误?是否应该以不同的方式从JSON对象中解析推文?

1 个答案:

答案 0 :(得分:3)

你忘记了逗号(time.time(),usernam ....等等。

澄清它将是

 c.execute("INSERT INTO tweets (tweet_time,     username, tweet) VALUES (%s,%s,%s)" ,
              (time.time(), username, tweet))