2013-10-08 48 views
0

我在使用Python方面很新穎,而且我正在尋找將Twitter數據收集到我的MySQL數據庫中的一個項目。我有我的劇本從本教程中收集數據:插入到mysql數據庫而不是打印

import re 
from re import sub 
import time 
import cookielib 
from cookielib import CookieJar 
import urllib2 
from urllib2 import urlopen 
import difflib 

cj = CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

keyWord = 'nyc' 
startingLink = 'https://twitter.com/search/realtime?q=' 

# begin loop 

def main(): 

    oldTwit = [] 
    newTwit = [] 
    while 1 < 2: 
     try: 
      sourceCode = opener.open ('https://twitter.com/search/realtime?q='+keyWord+'&src=hash').read() 
      splitSource = re.findall (r' <p class="js-tweet-text tweet-text">(.*?)</p>',sourceCode) 
      for item in splitSource: 
       #print item 
       print '' 
       print '' 
       print '       ' 
       aTweet = re.sub(r'<.*?>', '',item) 
       print aTweet 
       newTwit.append(aTweet) 

      comparison = difflib.SequenceMatcher(None, newTwit, oldTwit) 
      howSim = comparison.ratio() 
      print '##############' 
      print howSim 

      oldTwit = [None] 
      for eachItem in newTwit: 
       oldTwit.append(eachItem) 

      newTwit = [None] 

      time.sleep(howSim*10) 

     except Exception, e: 
      print str(e) 
      print 'errored in the main try' 
      time.sleep(555) 

main() 

這爲我提供了我想要收集(我真的不希望分析這些數據的鳴叫,我多用自動收集數據使用試驗蟒蛇連接到我的分貝)

我也有使用MySQLdb的我的數據庫連接,並且是能夠使用簡單的INSERT語句將內容添加到我的數據庫。

import MySQLdb 
db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="twitinfo") 
cursor = db.cursor() 
sql = "INSERT INTO tweets(text) VALUES ('?')" 
cursor.execute(sql) 
db.commit() 

所以我的問題是我怎麼能'用我的插入語句替換'打印,以及我該怎麼做需要添加以使我的價值成爲推文文本?我搜索了高和低,我沒有找到任何有用的東西。我也嘗試過自己,但作爲一個Python新手,試圖猜測它的語法就像在大海撈針中找到針。

回答

0

您顯示的SQL將包含單個問號的字符串插入到數據庫中。您需要使用VALUES(?)指定的值的佔位符,你需要一個值傳遞給執行功能,它插入,也許是這樣的:

sql = "INSERT INTO tweets(text) VALUES (?)" 
value = "Apoplectic Fits" 
cursor.execute(sql, value) 

您需要導入行添加到您的Python在頂部並連接到循環外部的DB。你可以把光標創建線放在循環之外。在循環中,您使用您的推文消息代替value


(使用新的模塊時,推薦的做法)閱讀文檔MySQLdb後,您需要使用%s的佔位符,而不是?

如果要插入的變量aTweet的數據,那麼:

sql = "INSERT INTO tweets(text) VALUES (%s)" 
cursor.execute(sql, aTweet) 

未經檢驗。理論上,理論和實踐沒有區別;在實踐中,有。

+0

SQL使用問號作爲佔位符。您需要找到[MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html)模塊的文檔,以查看我所猜測的是如何使用值執行SQL是否正確;看起來我已經足夠接近了。有一個古怪的功能;這些例子至少使用'%s'而不是'?'來表示值的放置位置。 –

+0

哦,我明白了,謝謝,這很有幫助。我可以使用我用來打印的相同變量嗎?我將其添加到所述插入件的命令: 主() SQL = 「INSERT INTO解析(文本)VALUES(aTweet)」 cursor.execute(SQL) db.commit() cursor.execute(SQL) db.commit() 我認爲我在正確的軌道上,我沒有得到語法錯誤,並且腳本仍然在編輯後拉入推文,但我的表仍然返回0行。 http://screencast.com/t/vwCFOZWL – user2770466

+0

查看最新的答案。 –