Python读取json文件并放入SQLite

时间:2013-11-07 03:16:09

标签: python json twitter

我遇到以下代码时遇到两个问题(至少)。

我的目标是读取每条推文,用JSON解析变量并将其放入SQLlite中自己的行中。在推文中的所有变量中,我只想要其中的六个。

我能够很好地阅读推文(并且创建的数据库和表没有问题)。

1)我的创建词典出错了。它声明“dictt not defined”。 (我之前已经开始工作了,但是为了不再工作而做了一些事情)。

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()

1 个答案:

答案 0 :(得分:0)

注意:您不需要:推文中的推文,因为“推文”包含字符串内容而不是JSON!

所以关于你的代码尝试在“加载”之前获得“转储”:

try:
    tweets = json.dumps(tweets)
    dictt = json.loads(tweets)
except ValueError:
    pass #other codes

“dumps”会将您的字符串转换为JSON。

之后你可以测试“dictt”:

for i in dictt:
    print i

您的代码可以是:

#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()

#create dictionary
try:
    tweets = json.dumps(tweets)
    dictt = json.loads(tweets)
except ValueError:
    print "invalid data"

for i in dictt:
    try:
        print json.loads(i).get('user').get('name')
        #print json.loads(i)['user']['name']
    except ValueError:
        print "can't read"

之后,您可以将数据保存在数据库中。