1. Learn
  2. /
  3. Courses
  4. /
  5. Building Chatbots in Python

Exercise

Basic negation

Quite often, you'll find your users telling you what they don't want - and that's important to understand! In general, negation is a difficult problem in NLP. Here, we'll take a very simple approach that works for many cases.

A list of tests called tests has been defined for you. Explore it in the Shell - you'll find that each test is a tuple consisting of:

  • A string containing a message with entities.
  • A dictionary containing the entities as keys and a Boolean saying whether they are negated as the key.

Your job is to define a function called negated_ents() which looks for negated entities in a message.

Instructions

100 XP
  • Using list comprehension, check if the words "south" or "north" appear in the message and extract those entities.
  • Split the sentence into chunks ending with each entity. To do this:
    • Use the .index() method of phrase to find the starting index of each entity e and add the entity's length to it to find the index of the end of the entity.
    • Starting with start=0, take slices of the string from start to end for each end in ends. Append each slice of the sentence to the list, chunks. Ensure you update your starting position with each iteration.
  • For each entity, if "not" or "n't" appears in the chunk, consider this entity negated.