PacktPublishing / Mastering-spaCy

Mastering spaCy, published by Packt
MIT License
125 stars 73 forks source link

Recognizing the intent using wordlists #7

Closed zebrassimo closed 2 years ago

zebrassimo commented 2 years ago

Most likely due to a spaCy upgrade to 3.0 the book code doesn't work, here's the better version. Corrections in comments.

doc   = nlp("i want to make a reservation for a flight")
dObj  = None
tVerb = None

#extract the direct object and its transitive verb
for token in doc:
    if token.dep_ == "dobj":
        dObj = token      
        tVerb= token.head 

# extract the helper verb
intentVerb = None

verbList = ["want","like","need","order"]
if tVerb.text in verbList:
    intentVerb = tVerb
else:
    if tVerb.head.dep_ == "ROOT":
        intentVerb = tVerb.head # <---------- intentVerb instead of helperVerb

#extract the object of the intent
intentObj = None
objList = ["flight","meal","booking"]
if dObj.text in objList:
    intentObj=dObj 
else:
    for child in tVerb.children: # <---------- this was dObj instead of tVerb
        if child.dep_ == "prep":
            intentObj= list(child.children)[0]
            break
        elif child.dep_ == "compound":
            intentObj = child
            break

print(intentVerb.text+intentObj.text.capitalize())

The graph now looks a little different, so need to look for the prep link from the root's children. displacy.render(doc,style='dep') shows:

Bildschirmfoto 2021-10-26 um 17 43 46
zebrassimo commented 2 years ago

.