2012-02-24 4 views
1

아래 코드는 모든 트윗을 콘솔에 출력하는 변수에 대한 트위터 공개 타임 라인을 스트리밍합니다. 같은 변수 (status.text, status.author.screen_name, status.created_at, status.source)를 sqlite 데이터베이스에 저장하고 싶습니다. 내 스크립트가 트윗을보고 sqlite 데이터베이스에 아무 것도 쓰지 않으면 구문 오류가 발생합니다.tweepy stream to sqlite 데이터베이스 - 잘못된 synatx

오류 :

$ 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) 
+0

문맥 오류가있어서 문맥을 좀 더 가질 수 있습니까? – jmlane

답변

2

당신은 다음의 마지막 줄에 닫는 괄호를 누락 코드 (34 ~ 37 행) 게시 됨) :

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

튜플 매개 변수 바로 뒤에 메서드 호출을 닫으려면 괄호를 추가하기 만하면됩니다.

+0

고마워요. –

+0

문제 없습니다. 두 번째 눈 쌍이 오타를 잡는 데 도움이됩니다. 논리적으로 대비되는 색 구성표에서 구문 강조를 사용하여 편집자가 이러한 오류를 피하거나 찾도록 도울 수 있습니다. – jmlane

+0

내 스크립트가 트윗을보고 sqlite 데이터베이스에 아무 것도 쓰지 않으면 구문 오류가 발생합니다. –

2
import sqlite3 as lite 
con = lite.connect('test.db') 
cur = con.cursor() 

cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") 

:

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

오류가 발생했습니다. 나는 그것이 올바르게했다라고 생각한다. ', 온라인 파일 "stream-v5.py"예외, 전자를 제외한 39 : ^ 구문 에러 : 유효하지 않은 구문 ' http://pastebin.com/mLqwUa16 나는 여전히 구문 오류 때 받고 있어요 –

+0

내 스크립트가 트윗을보고 sqlite 데이터베이스에 아무 것도 기록되지 않습니다. –

+0

죄송합니다. SQL 호출에서 매개 변수가 너무 적습니다. cur.executemany ("INSERT INTO TWEETS (?,?,?,?)", (status.text, status.author.screen_name, status.created_at , status.source)) – cbz

0

전체 공개 : 아직이 새로운 내용. 그러나 코드를 다음과 같이 변경하여 작동하도록했습니다.

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

한 번에 한 가지 상태로 읽는 것 같습니다. executemany 메소드는 둘 이상의 상태가있을 때 사용할 수 있습니다. 예를 들어 :

(['sometext', 'bob','2013-02-01','Twitter for Android'], ['someothertext', 'helga', '2013-01-31', 'MacSomething'])

확실히 마법사 아니에요하고있다) (가) (커밋 영향 어떤 종류의 확실하지 오전 모든 항목에 ... 난 성능을 추측하고있어 끔찍하지만, 그것을 작동합니다 쿼리의 단일 용어에 대한

코드를 게시 해 주셔서 감사 드리며, 결국 스트리밍하는 법을 배웠습니다.

0

나는 tweepy에 새로워졌습니다. 그러나 이것들은 저에게 효과가있는 수정들입니다. INSERT INTO TWEETS 뒤에 VALUES를 추가해야합니다. 또한 변경 사항을 커밋하는 것을 잊지 마십시오. 내가 언급 한 링크입니다 : related post

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

    con.commit()