【发布时间】:2013-11-07 03:16:08
【问题描述】:
下面的代码(至少)有两个问题。
我的目标是读取每条推文,用 JSON 解析一个变量,并将其放入 SQLlite 中自己的行中。在推文中的所有变量中,我只想要其中的六个。
我可以很好地阅读推文(数据库和表的创建没有问题)。
1) 我的创建字典出错。它声明“dictt未定义”。 (我早些时候让它工作,但做了一些事情让它不再工作)。
2) 当 dictt 工作时,只会加载第一条推文。我希望加载所有推文。所以这个循环有问题。
帮忙?
#Created the DB
import sqlite3
conn = sqlite3.connect('twitter.db')
c = conn.cursor()
#Created the table for the tweets
c.execute("CREATE TABLE IF NOT EXISTS Tweet(created_at, id, text, source, in_reply_to_user_ID,retweet_Count)")
import json
import urllib2
#Read file and print a line
webFD = urllib2.urlopen("http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/assignment4.txt")
tweets = webFD.readlines()
#prints all tweets
for tweet in tweets:
print tweet
#create dictionary
try:
dictt = json.loads(tweet)
except ValueError:
continue
#print dictionary to verify
print dictt.keys()
#print values to verify
print dictt.values()
#to load all parsed tweets into sqlite
for elt in tweets:
currentRow = elt[:-1].split(", ")
c.execute('INSERT INTO Tweet VALUES (?, ?, ?, ?, ?, ?)',
(dictt['created_at'], dictt["id"], dictt["text"], dictt['source'], dictt['in_reply_to_user_id'],
dictt['retweet_count']))
conn.commit()
conn.close()
【问题讨论】: