Assigning roles using spaCy's parser
In this exercise you'll use spaCy's powerful syntax parser to assign roles to the entities in your users' messages. To do this, you'll define two functions, find_parent_item() and assign_colors(). In doing so, you'll use a parse tree to assign roles, similar to how Alan did in the video.
Recall that you can access the ancestors of a word using its .ancestors attribute.
This exercise is part of the course
Building Chatbots in Python
Exercise instructions
- Create a
spacydocument calleddocby passing the message"let's see that jacket in red and some blue jeans"to thenlpobject. - In the
find_parent_item(word)function, iterate over theancestorsof eachworduntil anentity_type()of"item"is found. - In the
assign_colors(doc)function, iterate over thedocuntil anentity_typeof"color"is found. Then, find the parent item of thisword. - Pass in the
spacydocument to theassign_colors()function.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create the document
doc = ____
# Iterate over parents in parse tree until an item entity is found
def find_parent_item(word):
# Iterate over the word's ancestors
for parent in ____:
# Check for an "item" entity
if entity_type(____) == "____":
return parent.text
return None
# For all color entities, find their parent item
def assign_colors(doc):
# Iterate over the document
for word in ____:
# Check for "color" entities
if entity_type(word) == "____":
# Find the parent
item = ____
print("item: {0} has color : {1}".format(item, word))
# Assign the colors
____