#!/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('', boldtext) html = html.replace('', 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:]))