title: Determining proximity between 2 words in a sentence in Python
body: <p>I need to determine proximity between 2 words in a sentence in Python. For example, in the following sentence :</p>
  
  <pre><code>the foo and the bar is foo bar
  </code></pre>
  
  <p>I want to determine the distance between the words <code>foo</code> and  <code>bar</code> (determine number of words occurring between <code>foo</code> and  <code>bar</code>).</p>
  
  <p>Please note that there are multiple occurrences of the words <code>foo</code> and  <code>bar</code> in the above sentence producing different distance combinations. </p>
  
  <p>Also, order of the words shouldn't matter.  What is the best way to determine the distance between these words?</p>
  
  <p>Here is the code I am using :</p>
  
  <pre><code>sentence = "the foo and the bar is foo bar"
  
  first_word_to_look = 'foo'
  second_word_to_look = 'bar'
  
  first_word = 0
  second_word = 0
  dist = 0
  
  if first_word_to_look in sentence and second_word_to_look in sentence:
  
      first_word = len(sentence.split(first_word_to_look)[0].split())
      second_word = len(sentence.split(second_word_to_look)[0].split())
  
      if first_word &lt; second_word:
          dist = second_word-first_word
      else:
          dist = first_word-second_word
  
  print dist  # distance
  </code></pre>
  
  <p>The problem with the above code is that it only considers first occurrences of both the words. If there are more occurrences in same sentence that are even closer than first one, it doesn't consider it.</p>
  
  <p>What is the best way to determine the proximity ? Is there any library in python that can do this job better ?</p>