import_to_mongo.py 1.18 KB
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