【问题标题】:Python reading json file and placing into SQLlitePython 读取 json 文件并放入 SQLite
【发布时间】: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()

【问题讨论】:

    标签: python json twitter


    【解决方案1】:

    注意:对于推文中的推文,您不需要 :,因为“推文”具有字符串内容而不是 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"
    

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

    【讨论】:

    • 这给了我一个 SyntaxError: 'continue' not proper in loop。 NameError: 名称 'dictt' 未定义
    • 现在得到一个:AttributeError: 'unicode' object has no attribute 'keys' on the loop: step.与值相同。
    猜你喜欢
    • 2014-01-28
    • 2019-11-27
    • 2013-12-08
    • 2016-07-28
    • 2012-07-22
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    相关资源
    最近更新 更多