Esempio n. 1
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. 2
0
File: dict.py Progetto: ethinx/kaa
 def __init__(self, bot):
     super(Dict, self).__init__(bot)
     api_key = "fe5551798340efd8e52320db20103aa284241a2ccaea01d6f"
     user = "******"
     pw = "v0x"
     self._dict = Wordnik(api_key, user, pw)
     self._define()
Esempio n. 3
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. 4
0
 def __init__(self, rows=15, columns=15, api_key=None):
     """Create a `rows` X `columns` grid and initialize the clues dict.
     
     If `api_key` is not set then the key in config.py is tried.
     """
     self.grid = Grid(rows, columns)
     self.clues = {}
     api_key = api_key or config.WORDNIK_API_KEY
     if not api_key:
         raise WordnikAPIKeyError('Enter your Wordnik API key in config.py')
     self.wordnik = Wordnik(api_key)
     self._current_sq_id = 1  # To keep track of Square IDs
Esempio n. 5
0
 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)
Esempio n. 6
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. 7
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. 8
0
from django.conf.urls.defaults import *
from wordnik import Wordnik

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

w = Wordnik(api_key="1d3baf57f57254b5c430200e729037e9dea9d87493f3a16b4")
urlpatterns = patterns(
    '',
    (r'^(?P<mode>.*)/$', 'play.views.index', {
        "w": w
    }),
    #(r'^mix$', 'play.mix.index', { "w": w } ),
    # Example:
    # (r'^wordrainbow/', include('wordrainbow.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # (r'^admin/', include(admin.site.urls)),
)
Esempio n. 9
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'

Esempio n. 10
0
class CrosswordPuzzle(object):
    """A crossword puzzle grid that automatically generates puzzles.

    A `m` by `n` grid is populated with words from Wordnik's corpus. Currently
    the resulting crossword puzzle cannot have parallel, adjacent words like you
    would find in the NY TImes crossword.
    
    The grid itself is accessible through the __getitem__ method of the puzzle,
    which provides access to the individual Squares. Clues are taken from 
    Wordnik (definitions, example usages, synonyms, etc.) and are stored in a
    dictionary from clue positions to words and clues:
        self.clues[1, 'DOWN'] => ('cat', 'A small domestic animal')


    In order to create the puzzle you can use the populate_puzzle method, which
    uses Wordnik's Word of the Day as the first word and then adds the specified
    number of words to the puzzle. 
    """

    def __init__(self, rows=15, columns=15, api_key=None):
        """Create a `rows` X `columns` grid and initialize the clues dict.
        
        If `api_key` is not set then the key in config.py is tried.
        """
        self.grid = Grid(rows, columns)
        self.clues = {}
        api_key = api_key or config.WORDNIK_API_KEY
        if not api_key:
            raise WordnikAPIKeyError('Enter your Wordnik API key in config.py')
        self.wordnik = Wordnik(api_key)
        self._current_sq_id = 1  # To keep track of Square IDs

    def __str__(self):
        """Return the grid as a string."""
        return str(self.grid)

    def populate_puzzle(self, word_count):
        """Try to `word_count` words/clues. Return the number of words added."""
        words_added = 0
        if not self.clues:
            self.place_first_word()
            word_count -= 1
            words_added += 1

        for i in range(word_count):
            result = self.find_and_add_a_word()
            if result is None:
                s = 'Grid filled up after adding %d words.' % len(self.clues)
                print >> sys.stderr, s
                break
            else:
                words_added += 1

        self.finalize()
        return words_added

    def place_first_word(self, word=None):
        """Add the Wordnik Word of the Day as the first word in the puzzle.
        
        If no word is passed in, the Wordnik Word of the Day is used. 
        """
        if word is None:
            word = self.wordnik.word_of_the_day()['wordstring']

        #TODO: handle the WOTD being too long
        assert len(word) <= self.grid.num_columns, 'First word is too long.'
        span = [(0, n) for n in range(len(word))]
        self.add_word(word, span)
            
    def find_and_add_a_word(self):
        """Find a word in the Wordnik corpus that fits the puzzle and add it.
        
        If the search and addition are successful, return the wordstring. If
        not, return None.
        """
        open_spans = sorted(self.grid.open_spans(), key=len, reverse=True)
        for span in open_spans:
            query = ''.join([str(self.grid[m, n]) for (m, n) in span])
            query = query.replace(' ', '?')
            length = len(query)
            words = self.wordnik.word_search(query, max_length=length, 
                                             min_dictionary_count=1)
            if words:
                word = max(words, key=lambda w: w['count'])
                self.add_word(word['wordstring'], span)
                return word['wordstring']
        return None

    def store_clue(self, word, id_, direction, clue):
        """Store a word in self.clues. Call after putting word on the grid."""
        self.clues[id_, direction] = (word, clue)


    def add_word(self, word, span):
        """Place the word on the grid then add it and its clue to self.clues."""
        print >> sys.stderr, 'Placing word "%s".' % word
        self.put_word_on_grid(word, span)
        
        m, n = span[0][0], span[0][1]
        first_square = self.grid[m, n]
        if first_square.id_ is None:
            id_ = self._current_sq_id
            self._current_sq_id += 1
            first_square.id_ = id_
        else:
            id_ = first_square.id_
        definitions = self.wordnik.definitions(word)
        definition = random.choice(definitions)['text']
        direction = self.grid.get_span_direction(span)
        
        self.store_clue(word, id_, direction, definition)

    def put_word_on_grid(self, word, span):
        """Add the nth letter in `word` to the nth position in `span`.  """
        assert len(word) == len(span)
        assert len(span) > 1, "Can't insert word shorter than two letters."
        for i, char in enumerate(word):
            (m, n) = span[i]
            if self.grid[m, n].letter is None:
                self.grid[m, n].letter = char
            else:
                assert self.grid[m, n].letter == char

        # Black out open squares on either end of the word if they exist.
        direction = self.grid.get_span_direction(span)
        if direction == 'ACROSS':
            for (m, n) in ((m, n - 1), (m, n + 1)):
                if self.grid.are_valid_coordinates(m, n):
                    self.grid.blackout_square(m, n)

        elif direction == 'DOWN':
            for (m, n) in ((m - 1, n), (m + 1, n)):
                if self.grid.are_valid_coordinates(m, n):
                    self.grid.blackout_square(m, n)
        else:
            assert False, "Sanity check"

    def finalize(self):
        """Perform cleanup after all the words have been placed."""
        self.grid.blackout_all_open_squares()

    #
    # Gameplay related methods
    #
    @property
    def is_completed(self):
        """Return True if the user's entries match the correct letters."""
        for sq in self.grid:
            if sq.letter != sq.user_entry:
                return False
        return True

    def enter_from_user(self, m, n, letter):
        """Set the value of the square at (`m`, `n`) to `letter`."""
        sq = self.grid[m, n]
        assert not sq.is_blacked_out
        sq.letter = letter
Esempio n. 11
0
# Exceptions
from wordnik import RestfulError, InvalidRelationType, NoAPIKey, MissingParameters

# Globals
from wordnik import DEFAULT_URL, DEFAULT_FORMAT

from wordnik import Wordnik
Wordnik._populate_methods()

Esempio n. 12
0
#!/usr/bin/env python

import httplib, json, random, sys

from wordnik import Wordnik

w = Wordnik(api_key="d92d8109432f0ead8000707303d0c6849e23be119a18df853",
            username="******",
            password="******")


def add_word(word):
    token = w.token
    key = w._api_key
    headers = {
        "api_key": key,
        "auth_token": token,
        'Content-Type': 'application/json'
    }

    conn = httplib.HTTPConnection("api.wordnik.com")

    uri = "/v4/wordList.json/wordrainbow/words?username=wordrainbow"
    body = json.dumps([{
        "word": word,
    }])

    print body
    conn.request("POST", uri, body, headers)
    r = conn.getresponse()
    return r.status, r.reason
Esempio n. 13
0
#this can be done from the commandline by typing: easy_install Wordnik
try:
    from wordnik import Wordnik
except ImportError:
    raise NecessaryModuleNotFound(
        "Wordnik library not found. Please install wordnik library! e.g. sudo easy_install wordnik"
    )

#You need a wordnik api key, you can get yours at http://developer.wordnik.com/ (first you sign up for a username in the upp$
########################################################

wordnik_api_key = APIKeyForAPI("wordnik")

#########################################################

w = Wordnik(api_key=wordnik_api_key)


class define(Plugin):
    @register("en-US", "define ([\w ]+)")
    def defineword(self, speech, language, regMatched):
        Question = regMatched.group(1)
        output = w.word_get_definitions(Question, limit=1)
        if len(output) == 1:
            answer = dict(output[0])
            if u'text' in answer:
                worddef = answer[u'text']
                if worddef:
                    self.say(
                        worddef, "The definition of {0} is: {1}".format(
                            Question, worddef))
Esempio n. 14
0
web.config.debug = False

urls = (
    '/mix',         'Mix',
    '/identify',    'Identify',
    '/visualize',   'Visualize',
    '/play',        'Play',
    '/',            'Index',
)

alnum = map(chr, range(97, 123)) + [str(n) for n in range(0,10)]
KEY="d92d8109432f0ead8000707303d0c6849e23be119a18df853"
# w = Wordnik(api_key="1d3baf57f57254b5c430200e729037e9dea9d87493f3a16b4",username="******",password="******")
## privileged key!
wnk = Wordnik(api_key=KEY,username="******",password="******")
all_colors = uberList([ w['word'] for w in json.loads(wnk.word_list_get_words("wordrainbow")) ])
hexen = create_hexen()

class Mix(object):
    def GET(self):
        web.header("Access-Control-Allow-Origin", "*")
        
        if session.get("mixing", False):
            return self.mix()
        else:
            return self.initialize_session()
    
    
    def mix(self):
        query_params = web.input(name=None,hex=None,callback="callback")