Esempio n. 1
0
File: dict.py Progetto: ethinx/kaa
class Dict(Plugin):
    """usage: ^dict [word]"""

    def __init__(self, bot):
        super(Dict, self).__init__(bot)
        api_key = "fe5551798340efd8e52320db20103aa284241a2ccaea01d6f"
        user = "******"
        pw = "v0x"
        self._dict = Wordnik(api_key, user, pw)
        self._define()

    @Plugin.command("^dict")
    def _define(self, *args, **kwargs):
        query = kwargs.get("args", "")
        results = self._dict.word_get_definitions("{0}".format(query), limit=1)
        results = json.loads(results)

        if not results:
            error = "Request error: no results"
            self.reply(error)
            self.logger.warning(error)
        else:
            defi = results[0]["text"]
            part = results[0]["partOfSpeech"]
            word = results[0]["word"]
            result = chr(2) + word + chr(2) + " -- " + part + " -- " + defi
            self.reply(result)
Esempio n. 2
0
	def queryWordInfo(self,word):
		"""Queries the wordnik database for the definition and usage of specified
		word and returns the result as a tuple pf the form: (definition, usage).
		
		Keyword Parameters:
		word -- word to query the wordnik database for
		"""
		word = word.rstrip()
		word = word.lstrip()
		w = Wordnik(api_key="<ENTER WORDNIK API KEY>")
		query_result = w.word_get_definitions(word,sourceDictionaries='wiktionary')
		
		definition = ""
		usage = ""		
		
		usage_counter = 1
		definition_counter = 1
		
		#Wiktionary API has a strange way of returning multiple results with the same content
		#So, we index each obtained result to make sure that there are no repetitions.
		prev_parsed_definitions = []
		prev_parsed_usage = []
		
		for each_entry in query_result:			
			if "text" in each_entry.keys():
				curr_definition = each_entry["text"]
				if curr_definition not in prev_parsed_definitions:				
					prev_parsed_definitions.append(curr_definition)
					definition = definition + str(definition_counter) + "." + curr_definition + "\n"
					definition_counter = definition_counter + 1			
			
			#For Usage examples from Websters
#			if "citations" in each_entry.keys():
#				usage_list = each_entry["citations"]					
#				for each_entry in usage_list:
#					if "cite" in each_entry.keys() and "source" in each_entry.keys():
#						usage = usage + each_entry["cite"] + "\n\t\t\t--" + each_entry["source"] + "\n"

			#Usage examples from Wiktionary	
			if "exampleUses" in each_entry.keys():
				usage_list = each_entry["exampleUses"]					
				for each_entry in usage_list:
					if "text" in each_entry.keys():
						curr_usage = each_entry["text"]
						if curr_usage not in prev_parsed_usage:
							prev_parsed_usage.append(curr_usage)
							usage = usage + str(usage_counter) + "." + curr_usage + "\n"
							usage_counter = usage_counter + 1
		
		return json.dumps((definition,usage),indent=4)
Esempio n. 3
0
        def request_to_server(self, word):
            from wordnik import Wordnik
            bar_id = self.statusbar.get_context_id('statusbar')
            gtk.gdk.threads_enter()
            self.statusbar.push(bar_id, 'Request to server...')
            gtk.gdk.threads_leave()
            try:
                w = Wordnik(api_key='dd675e8c15076cfab74220264da05468a5f14d1e46b5f63cc')
                definitions = w.word_get_definitions(word)
                examples = w.word_get_examples(word)
                related = w.word_get_related(word)
            except:
                definitions = False
                examples = False
                related = False


            if definitions:
                # colect name for all partOfSpeech in definitions
                p_o_s = []
                for i in definitions:
                    if not(i['partOfSpeech'] in p_o_s):
                        p_o_s.append(i['partOfSpeech'])
                p_o_s.sort()

                # write definitions
                my_iter = self.buffer.get_start_iter()
                for p in p_o_s:
                    tmp = p.capitalize() + '\n'
                    self.buffer.insert_with_tags_by_name(my_iter, tmp, 'header')
                    for d in definitions:
                        if d['partOfSpeech']==p:
                            self.buffer.insert(my_iter, d['text'])
                            self.buffer.insert(my_iter, '\n\n') 


            if examples:
                # write examples
                my_iter = self.buffer_2.get_start_iter() 
                for p in examples['examples']:
                    title = p['title'] + '\n'
                    text = p['text'] + '\n'
                    self.buffer_2.insert_with_tags_by_name(my_iter, title, 'title')
                    self.buffer_2.insert(my_iter, text)
                    self.buffer_2.insert(my_iter, '\n\n')

                # highlighting words in examples
                search_str =  word
                start_iter =  self.buffer_2.get_start_iter()
                s = True
                while s:
                    found = start_iter.forward_search(search_str, 0, None)
                    if found:
                        match_start, match_end = found # add this line to get match_start and match_end
                        self.buffer_2.apply_tag_by_name('highlight', match_start, match_end)
                        start_iter =  match_end
                    else:
                        s = False

            if related:
                # write related
                my_iter = self.buffer_3.get_start_iter()
                for p in related[0]['words']:
                    text = p + '\n\n'
                    self.buffer_3.insert(my_iter, text)


            gtk.gdk.threads_enter()
            self.statusbar.pop(bar_id)
            if (definitions and examples and related):
                self.statusbar.push(bar_id, 'Request successfully completed.')
            else:
                self.statusbar.push(bar_id, 'Request Error. Try again later.')
            gtk.gdk.threads_leave()
Esempio n. 4
0
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)
Esempio n. 5
0
#!/usr/bin/python
from wordnik import Wordnik

word = Wordnik(api_key='1cc793b4b4ce10c19417b080bb20ecf919bdb5e01fb1eddfc')

x = ' '

while x:
    x = raw_input('\n\nplease enter a word: ')
    define = word.word_get_definitions(x)
    n = 0
    raw = 'y'
    try:
        print '\n', define[n]['text'].upper()
    except IndexError:
        print '\t\tNo Definition'.upper()
        break
    while raw[0] == 'y':
        x = raw_input('\nWould you like the next definition? (y or n): ').lower()
        if x and x[0] == 'y':
            try:
                n += 1
                print '\n', define[n]['text'].upper()
            except IndexError:
                print '\t\tno more definitions'.upper()
                continue
        else:
            break
print '\n\t\tGoodbye'