-
Notifications
You must be signed in to change notification settings - Fork 31
/
s.py
86 lines (61 loc) · 2.68 KB
/
s.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
# encoding: utf-8
"""
s.py
Created by Hilary Mason on 2010-08-15.
Copyright (c) 2010 Hilary Mason. All rights reserved.
"""
import sys, os
import re
import datetime
from optparse import OptionParser
import pymongo
import settings
from lib import mongodb
from lib import display
class Search(object):
def __init__(self, options, args):
self.debug = options.debug
self.db = mongodb.connect('tweets')
d = display.Display()
if options.user_search:
twitterers = self.user_search(options.user_search, int(options.num))
d.display_users(twitterers)
else:
tweets = self.tweet_search(args, int(options.num))
d.display_tweets(tweets)
def tweet_search(self, query_terms, num=10):
r = re.compile(' '.join(query_terms), re.I)
tweets = []
for t in self.db['tweets'].find(spec={'text': r }).sort('created_at',direction=pymongo.DESCENDING):
t['_display'] = True
t['_datetime'] = datetime.datetime.strftime(t['created_at'], "%I:%M%p, %b %d, %Y %Z")
tweets.append(t)
if self.debug:
print "%s total results" % (len(tweets))
return tweets[:num]
def user_search(self, user_terms, num=10):
r = re.compile(user_terms, re.I)
tweets = []
# search username
for t in self.db['users'].find(spec={'_id': r}).sort('_updated', direction=pymongo.DESCENDING):
t['_display'] = True
t['_datetime'] = datetime.datetime.strftime(t['_updated'], "%I:%M%p, %b %d, %Y %Z")
tweets.append(t)
usernames = [t['_id'] for t in tweets]
# search name
for t in self.db['users'].find(spec={'name': r}).sort('_updated', direction=pymongo.DESCENDING):
if t['_id'] not in usernames:
t['_display'] = True
t['_datetime'] = datetime.datetime.strftime(t['_updated'], "%I:%M%p, %b %d, %Y %Z")
tweets.append(t)
if self.debug:
print "%s total results" % (len(tweets))
return tweets[:num]
if __name__ == "__main__":
parser = OptionParser("usage: %prog [options] query terms")
parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False, help="set debug mode = True")
parser.add_option("-n", "--num", dest="num", action="store", default=10, help="number of tweets to retrieve")
parser.add_option("-u", "--user", dest="user_search", action="store", default=None, help="search users")
(options, args) = parser.parse_args()
t = Search(options, args)