usr bin env python coding utf-8 import re import urllib import simplej

 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
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urllib
import simplejson
import htmlentitydefs
def decode_entities(data, encoding=None):
"""Decode things like   to normal text"""
def unicode_char_callback(match):
code = match.group(1)
try:
value = unichr(int(code))
except ValueError:
value = code
return value
def entity_callback(match):
entity = match.group(1)
try:
value = htmlentitydefs.name2codepoint[entity]
try:
data = unichr(value)
if encoding:
data = data.encode(encoding)
return data
except UnicodeDecodeError:
pass
except KeyError:
pass
return u'&%s;' % entity
if encoding is None and isinstance(data, str):
try:
data = data.decode('utf-8')
except UnicodeDecodeError:
print 'data encoding is not unicode neither utf-8'
return ''
data = re.sub(r'&([a-z]+);', entity_callback, data)
data = re.sub(r'&#(\d+);', unicode_char_callback, data)
return data
colors = {"darkgrey": "\033[1m\033[30m",
"black": "\033[0m\033[30m",
"darkgreen": "\033[0m\033[32m",
"green": "\033[1m\033[32m",
"darkpurple": "\033[0m\033[35m",
"purple": "\033[1m\033[35m",
"brown": "\033[0m\033[33m",
"yellow": "\033[1m\033[33m",
"darkblue": "\033[0m\033[34m",
"blue": "\033[1m\033[34m",
"darkcyan": "\033[0m\033[36m",
"cyan": "\033[1m\033[36m",
"grey": "\033[0m\033[37m",
"white": "\033[1m\033[37m",
"darkred": "\033[0m\033[31m",
"red": "\033[1m\033[31m",
"neutral": "\033[0m",
"bold": "\033[0m\033[01m"}
def replace_html(html):
#redtext = "\033[31m"
#greentext = "\033[32m"
boldtext = "\033[1m"
normaltext = "\033[0m"
html = html.replace('<b>', boldtext)
html = html.replace('</b>', normaltext)
return html
def search(target):
baseurl = 'http://ajax.googleapis.com/ajax/services/search/web'
params = {}
params['v'] = '1.0'
params['q'] = target
url = baseurl+'?'+urllib.urlencode(params)
results = simplejson.load(urllib.urlopen(url))
for result in results['responseData']['results']:
#print result
#output = colors['blue']+":: "+colors['white']+self.REPO+'/'+self.NAME+"\n"
#output+= colors['grey']+"\t"+"Version".ljust(18)+": "+colors['white']+self.VERSION+"\n"
#output+= colors['grey']+"\t"+"Installed version".ljust(18)+": "+[colors['white'],colors['cyan'],colors['blue'],''][installed[0]]+str(installed[1])+"\n"
#print colors['darkcyan'] + 'Title:'.ljust(8) + colors['neutral'],
print replace_html(decode_entities(result['title']))+',',
print colors['darkcyan']+result['unescapedUrl']+colors['neutral']
#print '-', replace_html(result['content'])
if __name__ == '__main__':
import sys
if len(sys.argv)<2:
print 'Please specify what to search.'
else:
search(' '.join(sys.argv[1:]))