title: Obtaining left and right side words of entities with SpaCy
body: <p>I have been working on NLP project with SpaCy to obtain left and right side words of all entities and dump them to JSON format.</p>
  
  <p>Here is the function that I tried:</p>
  
  <pre><code>def __init__(self):
      self.new_side_words_json = dict()
  
  def side_words(self, text):
      words = nlp(text).ents[0]
      side_words_json = [{'LeftSideWord': str(words[entity.start - 1]),
                          'Entity': str(entity),
                          'RightSideWord': str(words[entity.end])}
                         if not words[entity.start - 1].is_punct 
                         and not words[entity.start - 1].is_space 
                         and not words[entity.end].is_punct
                         and not words[entity.end].is_space
                         else
                         {'LeftSideWord': str(words[entity.start - 2]),
                          'Entity': str(entity),
                          'RightSideWord': str(words[entity.end + 1])}
                         for entity in nlp(text).ents]
      self.new_side_words_json['SideWords'] = side_words_json
  </code></pre>
  
  <p>In some cases, this algorithm works. However, it is a quite ugly solution in my opinion as it does not control the conditions enough. This algorithm is highly dependent on text format. I would like to build something solid that works with every document. </p>
  
  <p>What I mean by that is, in the text file, there can be many punctuations or spaces one to another. I am just controlling two levels below or above.</p>
  
  <p>What I would like to do is, create an algorithm that finds the meaningful words that are previous and next to the entity but not punctuation or space or maybe not even stop-words.</p>
  
  <p>How can I tweak this algorithm to get the previous and next meaningful word of all entities?</p>