Thursday, December 30, 2010

A Wonderful, Fantastic, Grand, Marvelous, Howling and Extrodinary API

I needed a facility for finding related words. Luckily, I was able to find the Big Huge Thesaurus API.

As web services go, it's pretty dang near perfect:

  • You can get up and running with a free API key for testing purposes in a few seconds
  • The API is as simple as invoking a URL in the format: http://words.bighugelabs.com/api/2/API_KEY/WORD_TO_LOOKUP/
  • The API will return a variety of formats, from basic text to JSON and XML
  • It's hacker friendly, in that you can rig up a php CURL function in a few minutes, or even just test it out in your web browser

In fact, here's the PHP code I wrote to access it. Feel free to use and enjoy:

/*
 * Find related words. 'word' is the word to search for.
 * `narrow_to_relationship' will cause just matches of a particular relationship
 * to return.
 *
 * Leave off the second option to get back all results.
 *
 * Possible values for narrow_to_relationship: syn (synonym),
 * ant (antonyms), rel (related) and sim (similar).
 *
 * Return back an array of arrays of data -or an array of a specific
 * type of words.
 */
function find_related_words($word, $narrow_to_relationship = false) {
  $key = BIGHUGELABS_API_KEY;
  $url = "http://words.bighugelabs.com/api/2/$key/" . urlencode($word) . "/";

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 3);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  $lines = preg_split('/[\n\r]/', curl_exec($ch));

  $results = array();
  foreach($lines as $l) {
    $values = explode("|", $l);
    if($narrow_to_relationship) {
      if($narrow_to_relationship == $values[1]) {
        $results[] = $values[2];
      }
    } else {
      $results[] = array('part' => $values[0], 'relationship' => $values[1], 'word' => $values[2]);
    }
  }
  return $results;
}

// Sample Usage
$I_am_a = find_related_words("hacker"); // get back all terms related to hacker
$I_want_to_be = find_related_words("hacker", "syn"); // get back a list of synonyms

Using a thesaurus is a simple way to make a user's input seem a lot smarter. I'm actually surprised I've gone this long without integrating one into an app before. Luckily, using the facility was a breeze.

No comments:

Post a Comment