title: Get best synonym for words in sentences using wordnet
body: <p>I have done code to get synonyms from wordnet, and it is providing complete list of synonym for each word.
  So, I want my code to select appropriate synonym from synonym list based on sentence.</p>
  
  <p>For example: 
  Sentence is: "I am his older brother" and I have to find out best synonym for each word based on this sentence.</p>
  
  <p>Lets select "older". Wordnet would give synonym list for "older": </p>
  
  <p><em>['elder', 'onetime', 'former', 'sr.', 'one-time', 'erstwhile', 'honest-to-god', 'aged', 'Old', 'previous', 'sure-enough', 'older', 'senior', 'old', 'sometime', 'honest-to-goodness', 'quondam', 'elderly']</em></p>
  
  <p>From the list best synonym based on this sentence is 'elder', so it should be selected.</p>
  
  <p>How can I do this? </p>
  
  <p>Code to get synonyms:</p>
  
  <pre><code>from nltk.tokenize import word_tokenize
  from nltk.tag import pos_tag
  from nltk.corpus import wordnet as wn
  
  def tag(sentence):
   words = word_tokenize(sentence)
   words = pos_tag(words)
   return words
  
  def paraphraseable(tag):
   return tag.startswith('NN') or tag == 'VB' or tag.startswith('JJ')
  
  def pos(tag):
   if tag.startswith('NN'):
    return wn.NOUN
   elif tag.startswith('V'):
    return wn.VERB
  
  def synonyms(word, tag):
      lemma_lists = [ss.lemmas() for ss in wn.synsets(word, pos(tag))]
      lemmas = [lemma.name() for lemma in sum(lemma_lists, [])]
      return set(lemmas)
  
  def synonymIfExists(sentence):
   for (word, t) in tag(sentence):
     if paraphraseable(t):
      syns = synonyms(word, t)
      if syns:
       if len(syns) &gt; 1:
        yield [word, list(syns)]
        continue
     yield [word, []]
  
  def paraphrase(sentence):
   return [x for x in synonymIfExists(sentence)]
  get=[]
  get=paraphrase("I am his older brother")
  print("paraphrase",get)
  </code></pre>