Words API

From building a “Hyperloop” to getting a $1 billion investment from Google, it seems like Elon Musk is in the news almost every day. By now, reporters must be running out of superlatives to describe him. Even “genius” can lose its luster if you use it too much.

Anyone can pull up a thesaurus and start flipping, but perhaps you want to run a more thorough search, and maybe turn up something a bit more interesting. Not just synonyms, but also find words that are related in other ways. And maybe you would also like to limit the results to words that are used less frequently than “genius”.

That’s the kind of thing Words API can help with. Words API stores words in a graph-like structure, and you can explore that graph to find what you’re looking for. It also has data on how frequently a word is used, so we can use that to filter out the results.

Let’s write a little Node.js script to find words related to “genius”. We’ll make use of Mashape’s Unirest library to make request’s to Words API. Since we’ll be making numerous calls to Words API, we’ll wrap it in a function that takes a word and a callback.

function getWord( word, callback ){
    unirest.get("https://wordsapiv1.p.mashape.com/words/" + word )
		.header("X-Mashape-Key", yourMashapeKey)
		.header("Accept", "application/json")
		.end(function (result) {
			callback( result.body );
	});
}

The response contains JSON that looks like this:

{
  "word": "genius",
  "results": [
    {
      "definition": "unusual mental ability",
      "partOfSpeech": "noun",
      "synonyms": [
        "brilliance"
      ],
      "typeOf": [
        "intelligence"
      ],
      "hasTypes": [
        "pyrotechnics",
        "scintillation",
        "coruscation"
      ]
    },
    {
      "definition": "exceptional creative ability",
      "partOfSpeech": "noun",
      "synonyms": [
        "wizardry"
      ],
      "typeOf": [
        "creative thinking",
        "creativeness",
        "creativity"
      ]
    }
    // truncated list of definitions
    ]
}

The definitions, and words related to those definitions, are in the results array. Let’s grab those related words and store them in an array, filtering out relationships we’re not interested in. Again, we’ll be calling this often, so let’s wrap it in a function called addNodes, that takes an object that is the result of a call to Words API. We’ll only return new nodes that are along interesting edges (so we don’t grab things link antonyms). We’ll also skip verbs.

function addNodes( obj ){

    var res = [];

    var interestingEdges = [
        'synonyms',
        'hasTypes',
        'similarTo
    ];

    for ( var j = 0, jlen = obj.results.length; j < jlen; j++ ){
        var definition = obj.results[j];
        if (definition.partOfSpeech !== 'verb' ){
            for ( var i = 0, len = interestingEdges.length; i < len; i++ ){
                if ( definition[ interestingEdges[i] ] ){
                    res = res.concat( definition[ interestingEdges[i] ] );
                }
            }
        }
    }
    return res;
}

Here’s what our graph looks like so far. Words that are synonyms to genius are linked in red, while words that are types of genius are linked in blue. Not too many words so far, but that’ll change in a minute.

Genius - Words API graph

Now we can call getWord and addNodes for each of the edge words. After walking the graph at the second level, here’s what the graph looks like. Notice that many words are linked not only to the first level words, but also to other second level words.

Words API Second Level Graph

 

Now we have 164 words to choose from, but remember that we’re looking for words used less frequently than “genius”. So let’s sort our result by the frequency attribute that Words API returned for each result, and print out the results. Our list is stored in a javascript object called candidates, so we’ll convert that into an array while filtering out anything whose frequency is greater than “genius”. Then we’ll sort the array so the most infrequent words are at the top.

var infrequent = _.filter( _.toArray(candidates), function( word ){
    return word.frequency < candidates['genius'].frequency;
});

infrequent.sort( function( a, b ){
    if (a.frequency < b.frequency){
        return -1;
    } else if ( a.frequency > b.frequency ){
        return 1;
    }
    return 0;
});
var list = _.map(infrequent, function( word ){
    return word.word;
});
console.log(list.join(","));

We’re left with 143 words to choose from, with the most infrequently used words at the top:

sympathiser, mavin, coruscation, prognostic, prizewinning, eclat, proposer, enchanter, coruscation, sentience, sustainer, presage, pentangle, scintillation, modality, whig, masterly, elan, trailblazer, originator, prognostication, maven, maintainer, magus, portent, pentacle, paladin, anglophile, brainpower, loyalist, mainstay, partisan, innovator, panache, skilful, whizz, splendour, singleton, pyrotechnics, tiptop, witching, boswell, sympathizer, protagonist, masking, sorceress, masterful, supernova, wizardry, topnotch, necromancer, subscriber, stalwart, headliner, glisten, mover, foreboding, asterisk, odour, virtuoso, sensibility, nous, wiz, enthusiast, proficient, starlet, adept, magnificence, grandeur, supporter, binary, variable, skillful, stellar, voucher, pentagram, exorcist, consummate, splendor, prodigy, mastermind, brilliance, pillar, glare, sparkle, omen, sorcerer, prima, confederate, beginner, sparkling, glitter, pioneer, blaze, mentality, founder, flair, odor, skilled, subconscious, booster, unity, psyche, threshold, starring, idol, sensitivity, admirer, twinkle, practiced, superstar, believer, hotshot, toaster, whiz, flare, supernatural, sensation, einstein, nova, wit, dash, cheerleader, tops, ego, magician, magical, wizard, unconscious, fighter, superior, principal, ace, champ, champion, leading, expert, vision, super, giant, charming, style, crack

We definitely found some interesting words in there. Choosing the best one for the job is up to you, but I think I’d go with “magus” to describe Elon Musk. It has a nice alliterative feel with “Musk”, and I like the wizardly connotation.

For more fun things you can do with Words API, check out the documentation. If you’d like to play around with it, you can view this code on GitHub. You’ll need your own Mashape key to get it to work.

What are you waiting for?

category:
Share this: