class Lookup: ''' Looks up different stuff on Wordnick NB: no batch-processing - very slow! TODO: do batch-processing (using Wordnik.multi)? ''' def __init__(self, api_key): '''Initialize and check wordnik apu key''' puts(colored.blue('Using Wordnik API key: %s' % api_key)) self.w = Wordnik(api_key) try: stats = self.w.account_get_api_token_status() if(stats['valid']): puts(colored.green('OK, API key is valid.')) puts('Requests performed: \033[1m%s\033[0;0m Remaining calls: \033[1m%s\033[0;0m Quota reset in: \033[1m%s\033[0;0m' % ( stats['totalRequests'], stats['remainingCalls'], datetime.timedelta(milliseconds=stats['resetsInMillis']) ) ) puts(colored.blue('Commencing lookup (it may take a while)...')) except TypeError as e: raise Exception ('Wrong API key: %s' % e) def define(self, word): '''Get all available definitions''' annotations = ['Informal', 'Slang'] # TODO: add part of speech (in blue?) definitions = self.w.word_get_definitions(word) card_define = '' for definition in definitions: if 'text' in definition: card_define += annotate(definition['text'], annotations).lower() + u'<br />' return card_define def example(self, word): '''Get example sentences''' # TODO: sort by highest score! examples = self.w.word_get_examples(word) card_example = '' if 'examples' in examples: # Use no more than 2 example sentences (may also set limit for w_g_examples()) for example in examples['examples'][:2]: if 'text' in example: card_example += example['text'].replace(word, Decker.bold(word)) + u'<br />' return card_example def pronounce(self, word): '''Get pronounciation (in round brackets)''' pronunciations = self.w.word_get_pronunciations(word) if(pronunciations): try: return pronunciations[0]['raw'] except Exception: return u'' def phrase(self, word): '''Get phrases with this word''' phrases = self.w.word_get_phrases(word) card_phrase = [] for phrase in phrases: try: card_phrase.append(phrase['gram1'] + ' ' + phrase['gram2']) except Exception: pass if(card_phrase): return ' | '.join(card_phrase) + u'<br />' def batch(self, words): '''Batch lookup. Note, that it not always works as it should.''' calls = [] requests = ['definitions', 'examples', 'phrases', 'pronounciations'] for word in words: for request in requests: calls += (word, request) return self.w.multi(calls)