我试图从一个文件中读取1000条推文。在
http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/Twitter_2013_11_12.txt
这些tweet是逐行存储的。 我必须为'geo'条目创建一个SQL表Geo'是tweets字典中的一个字典。在某些情况下,字典“geo”是完全空白的,在某些情况下它有值。我需要记录下有多少地理词典是空白的,有多少有虚拟语言。我需要为那个表生成一个唯一的ID。除了ID列,geo表还应该有“type”、“longitude”和“latitude”列。如果Geo dictionary有值,则如下所示:
^{pr2}$因为我是Python和SQLITE的新手,所以我的代码是基本的(因为我希望能够理解我的代码),而且它没有按预期工作。我正在尝试在Geo表中插入,如果Geo字典的长度大于1,但它不起作用。如有任何意见,我们将不胜感激。在
import urllib2, time, json, sqlite3
conn = sqlite3.connect('Tweets_Database_A6.db')
c = conn.cursor()
wFD = urllib2.urlopen('http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/Twitter_2013_11_12.txt')
numLines = 1000
tweets = []
while numLines > 0:
line = wFD.readline()
numLines = numLines - 1
try:
tweets.append(json.loads(line))
except:
print line
wFD.close()
#create geo table using sqlite3
TblGeo = """create table Geo(Id number, Type text, Longitude number, latitude number);"""
c.execute(TblGeo)
HasGeo=0
NoGeo=0
for tweet in tweets:
tweet_geo = tweet['geo']
if len(tweet_geo) > 1:
HasGeo = HasGeo+1
try:
c.execute("insert into Geo(id, Type, Longitude, Latitude) values ('%s', '%s', '%s', '%s')" %(HasGeo, tweet_geo['type'], tweet_geo['coordinates'][0], tweet_geo['coordinates'][1]))
except:
print "no entry for " , i
else:
NoGeo = NoGeo+1
print HasGeo, " ", NoGeo
您的代码失败有几个原因。因为这似乎是一个任务,我不会在这里张贴工作代码,但我会试图指出你的正确方向。以下是我在测试代码时注意到的一些事情:
我希望这是有帮助的;如果你被难住了,请随时要求更多的澄清。在
相关问题 更多 >
编程相关推荐