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.
Este ejercicio forma parte del curso
Building Chatbots in Python
Instrucciones del ejercicio
- Create a
spacy
document calleddoc
by passing the message"let's see that jacket in red and some blue jeans"
to thenlp
object. - In the
find_parent_item(word)
function, iterate over theancestors
of eachword
until anentity_type()
of"item"
is found. - In the
assign_colors(doc)
function, iterate over thedoc
until anentity_type
of"color"
is found. Then, find the parent item of thisword
. - Pass in the
spacy
document to theassign_colors()
function.
Ejercicio interactivo práctico
Prueba este ejercicio completando el código de muestra.
# 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
____