Nahid Khan
Nahid Khan

Reputation: 11

How to get relation between words in a sentence using nlp

I am trying to get the relation between words in a sentence. Like if I have a sentence: "Remind me to leave work today at 12PM"

Here "Leave" and "work" has a relation which makes the word "Leave work" which is the name of the task.

But how can I do that? Is there any NLP trick? Please help me if you have any answer.

Upvotes: 0

Views: 821

Answers (1)

fsimonjetz
fsimonjetz

Reputation: 5802

One easier way to approach this problem is dependency parsing. Here is an example with the NLP library spaCy.

import spacy

# load nlp pipeline
nlp = spacy.load('en_core_web_sm')

# process document: incl. tokenization, pos-tagging, dependency parsing, ...
doc = nlp('Remind me to leave work today at 12PM')

# access dependency relations
for tok in doc:
    print(tok.head, '--->', tok, tok.dep_, sep="\t")

Dependency relations:

Remind   --->   Remind  ROOT
Remind   --->   me      dobj
leave    --->   to      aux
Remind   --->   leave   xcomp
leave    --->   work    dobj
leave    --->   today   npadvmod
leave    --->   at      prep
at       --->   12PM    pobj

This is equivalent to the tree below.

from spacy import displacy

# in Jupyter Notebook
displacy.render(doc, style="dep", options={'compact': True, 'distance': 120})

Dependency tree

From here, you can try to come up with constraints to extract the information you need, like "look for tokens that are tagged as VV and have a dobj relation", but the details really depend on your intended application.

Upvotes: 2

Related Questions