Skip to content

Instantly share code, notes, and snippets.

@metaskills
Last active August 29, 2015 14:16
Show Gist options
  • Save metaskills/4a56a3e0691a97aa8965 to your computer and use it in GitHub Desktop.
Save metaskills/4a56a3e0691a97aa8965 to your computer and use it in GitHub Desktop.
Ruby Solution To Phrase Synonym Count Winner
# 1) Write a function which takes a phrase.
# 2) Phrase is "May the force be with you"
# 3) Which of these words has the most synonyms
require 'json'
require 'net/http'
API_KEY = 'SECRET'
BASE_URL = "http://thesaurus.altervista.org/service.php?language=en_US&output=json&key=#{API_KEY}&word=";
def synonym_data(word)
uri = URI.parse "#{BASE_URL}#{word}"
JSON.parse Net::HTTP.get(uri)
end
def synonyms_from_data(data)
return [] if data['error']
lists = data['response']
lists.map { |list|
synonyms = list['list']['synonyms'].split('|')
synonyms.reject! { |s| s =~ /\(antonym\)/ } # Antonyms are not Synonyms.
synonyms.map { |s| s.sub /\s\(.*\)/, '' } # Remove things like " (related term)"
}.flatten.uniq
end
def synonym_count(word)
data = synonym_data(word)
synonyms_from_data(data).length
end
def phrase_to_words_and_synonym_count_hash(phrase)
words = phrase.split ' '
counts = words.map { |w| Thread.new(w) { |word| synonym_count(word) } }.collect(&:value)
Hash[words.zip(counts)]
end
def word_with_most_synonyms_from_phrase(phrase)
data = phrase_to_words_and_synonym_count_hash(phrase)
most = data.values.max
word = data.detect { |w,c| c == most }
{word: word[0], count: word[1]}
end
word_with_most_synonyms_from_phrase "May the force be with you" # => {word: "force", count: 62}
@metaskills
Copy link
Author

Made a few updates. The word_with_most_synonyms_from_phrase returns a Hash now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment