#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# File: en2pt.py
# Description: translate a word from english to portuguese
# Usage: 
#    $ ./en2pt.py word
#    1 - palavra: a) vocábulo, termo. b) fala. c) promessa.
#    2 - conversa breve, conversação.
#    ...

import re
import sys
import urllib2
import HTMLParser

#searching
url = 'http://michaelis.uol.com.br/moderno/ingles/index.php?lingua=ingles-portugues&palavra='
word = sys.argv[1]
html = urllib2.urlopen('%s%s' % (url, word)).read()

#patterns
definitions = lambda s: re.sub('\\s*<B>\\s*(\\d+)\\s*</B>\\s*', '\n\\1. ', s)
unescape    = lambda s: HTMLParser.HTMLParser().unescape(re.sub('\\s*&bull;\\s*', '\n', s))
clear       = lambda s: re.sub('<I>(\\s*)</I>', '', re.sub('<B>(\\s*)</B>', '', s)).replace('</P>', '')
italic      = lambda s: re.sub('<I>\\s*(.*?)\\s*</I>', '\033[92m\\1\033[0m', s)
bold        = lambda s: re.sub('<B>\\s*(.+?)\\s*</B>', '\n  \033[94m\\1\033[0m ', s)
format      = lambda s: italic(bold(definitions(clear(unescape(s)))))

#parsing
pattern = r"<span class='descricao'>\s*(.*?)\s*</span>"
for s in re.findall(pattern, html):
    print format(s)
    print
