import_to_mongo.py
1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json
import sys
import os
import datetime
from pymongo import MongoClient
if len(sys.argv) < 2:
print "Wrong number of arguments! Try: python", sys.argv[0], "tweets_directory"
sys.exit(1)
directory = sys.argv[1]
client = MongoClient()
db = client.trendminer
tweets = db.tweets
dirList = os.listdir(directory)
t = 0
errors = []
for file in sorted(dirList):
print "Processing", file
l = 0
with open(os.path.join(directory, file)) as f:
for line in f:
try:
l += 1
data = json.loads(line)
created_at = data["created_at"]
dt = datetime.datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')
data["created_at_mongo"] = dt
if "id" in data:
del data["id"]
if "user" in data and "id" in data["user"]:
del data["user"]["id"]
tweets.insert(data)
t += 1
except Exception as ex:
errors.append(line+str(ex))
print t, "tweets saved to database"
print len(errors), "tweets not saved to database"
print "Exceptions:"
for ex in errors:
print ex