Swapping infinitive phrases

An infinitive phrase has the form A of B, such as book of recipes. These can often be transformed into a new form while retaining the same meaning, such as recipes book.

How to do it...

An infinitive phrase can be found by looking for a word tagged with IN. The swap_infinitive_phrase() function, defined in transforms.py, will return a chunk that swaps the portion of the phrase after the IN word with the portion before the IN word:

def swap_infinitive_phrase(chunk):
  def inpred(wt):
    word, tag = wt
    return tag == 'IN' and word != 'like'

  inidx = first_chunk_index(chunk, inpred)

  if inidx is None:
    return chunk

  nnidx = first_chunk_index(chunk, tag_startswith('NN'), start=inidx, step=-1) or 0
  return chunk[:nnidx] + chunk[inidx+1:] + chunk[nnidx:inidx]

The function can now be used to transform book of recipes into recipes book:

>>> from transforms import swap_infinitive_phrase
>>> swap_infinitive_phrase([('book', 'NN'), ('of', 'IN'), ('recipes', 'NNS')])
[('recipes', 'NNS'), ('book', 'NN')]

How it works...

This function is similar to the swap_verb_phrase() function described in the Swapping verb phrases recipe. The inpred function is passed to first_chunk_index() to look for a word whose tag is IN. Next, we find the first noun that occurs before the IN word, so we can insert the portion of the chunk after the IN word between the noun and the beginning of the chunk. A more complicated example should demonstrate this:

>>> swap_infinitive_phrase([('delicious', 'JJ'), ('book', 'NN'), ('of', 'IN'), ('recipes', 'NNS')])
[('delicious', 'JJ'), ('recipes', 'NNS'), ('book', 'NN')]

We don't want the result to be recipes delicious book. Instead, we want to insert recipes before the noun book but after the adjective delicious, hence the need to find the nnidx occurring before the inidx.

There's more...

You'll notice that the inpred function checks to make sure the word is not like. That's because like phrases must be treated differently, as transforming them the same way will result in an ungrammatical phrase. For example, tastes like chicken should not be transformed into chicken tastes.

>>> swap_infinitive_phrase([('tastes', 'VBZ'), ('like', 'IN'), ('chicken', 'NN')])
[('tastes', 'VBZ'), ('like', 'IN'), ('chicken', 'NN')]

See also

In the next recipe, we'll learn how to transform recipes book into the more normal form recipe book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset