微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – tweyy流到sqlite数据库 – 无效的synatx

下面的代码是将Twitter公共时间线流式传输给变量,该变量将任何推文输出到控制台.我想将相同的变量(status.text,status.author.screen_name,status.created_at,status.source)保存到sqlite数据库中.当我的脚本看到推文并且没有任何内容写入sqlite数据库时,我收到语法错误.

错误

$python stream-v5.py @lunchBoxhq
Filtering the public timeline for "@lunchBoxhq"RT @LunchBoxHQ: test 2   LunchBoxHQ  2012-02-29 18:03:42 Echofon
Encountered Exception: near "?": Syntax error

编码:

import sys
import tweepy
import webbrowser
import sqlite3 as lite

# Query terms

Q = sys.argv[1:]

sqlite3file='/var/www/twitter.lBox.com/html/stream5_log.sqlite'

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

con = lite.connect(sqlite3file)
cur = con.cursor()
cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)")

class CustomStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        try:
            print "%s\t%s\t%s\t%s" % (status.text, 
                                      status.author.screen_name, 
                                      status.created_at, 
                                      status.source,)

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

        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e
            pass

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)

print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),)

streaming_api.filter(follow=None, track=Q)

解决方法:

您在以下代码的最后一行缺少右括号(与您发布的内容相同的第34-37行):

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

只需添加一个括号,即可在tuple参数后立即关闭方法调用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐