summaryrefslogtreecommitdiffstats
path: root/BlogSearchStats.py
blob: c214e7eaeddbc24bb37815448985a9b239b6eded (plain) (blame)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

from sys import argv
import csv
import string
from GoogleStats import blogSearchMonthResultCount
from time import sleep
from Emailer import sendFile
from Imdb import titleCode


def sanitizeString(dirty):
	clean = ""
	allowed = string.ascii_letters + string.digits + " -.'\""
	for i, v in enumerate(dirty):
		if allowed.find(str(v)) != -1:
			clean = clean + str(v)
		else:
			clean = clean + " "
	while clean.find("  ") != -1:
		clean = clean.replace("  ", " ")
	return clean.strip()

def tryTenTimes(function):
	count = 10
	while count > 0:
		count = count - 1
		try:
			return function()
		except Exception as ex:
			print "Error:", ex, "... sleeping 5."
			sleep(5)
	return None

emailMessage = "Hello %s,\n\nThis is an automated message. Attached are the requested blog statistics for these movies:\n" % argv[3][0:argv[3].find('@')]
listFile = open(argv[1])
outFile = open(argv[2], "wb")
output = csv.writer(outFile)
header = ["Rank", "Movie", "Google Blog Search Result Count (past month)", "IMDB Title Code"]
output.writerow(header)
print header
i = 0
for line in listFile:
	i = i + 1
	movie = line.strip()
	emailMessage = emailMessage + "\n    * %s" % movie
	searchString = sanitizeString(movie)
	blogSearch = tryTenTimes(lambda: blogSearchMonthResultCount(searchString))
	if blogSearch is None:
		blogSearch = '???'
	imdbTitleCode = tryTenTimes(lambda: titleCode(searchString))
	if imdbTitleCode is None:
		imdbTitleCode = '???'
	row = [str(i), movie, str(blogSearch), imdbTitleCode]
	output.writerow(row)
	outFile.flush()
	print row
outFile.close()
listFile.close()
emailMessage += "\n\nEnjoy,\nJason"
print "Sending email...",
sendFile(argv[3], argv[2], emailMessage)
print "sent!"