How to get a pair of dependency relation between two words in a sentence using spacy?

Viewed 568

I am using spacy to get the dependency relation, this works well. But I have a problem of getting a pair of token with a specific dependency relation (except for the conj relation).

When using the .dep_, I can get the dependency attribute of each seprate token. However, I would like to a pair of token for a specific dependency relation. For example, in the following code, I can get the shown result.

import spacy
nlp = spacy.load("en_core_web_md")
sentence = 'The Marlins were stymied by Austin Gomber and the Rockies in their 4-3 loss'
doc = nlp(sentence)
for token in doc:
    print (token, token.dep_)

Current output:

The det
Marlins nsubjpass
were auxpass
stymied ROOT
by agent
Austin compound
Gomber pobj
and cc
the det
Rockies conj
in prep
their poss
4 nummod
- punct
3 prep
loss pobj

But what I desire to get is: (please ignore the output style, I only want to get a pair of token with a specific dependency relation, e.g., here is pobj)

'Gomber' is a 'pobj' of 'by'
'Loss' is a 'pobj' of 'in'

In another word, I do not only want to get the result of current output, I also want to get paired token for each word.

For the conj dependency relation, I can get them simply by just using token.conjuncts, but for the rest of other dependency relations, such the pobj, prep, I have not found any method can be used directly in spacy.

Does anyone have a hint on getting this pobj relation? Thanks in advance!

1 Answers

You can use the head index. E.g.,

tok_l = doc.to_json()['tokens']
for t in tok_l:
  head = tok_l[t['head']]
  print(f"'{sentence[t['start']:t['end']]}' is {t['dep']} of '{sentence[head['start']:head['end']]}'")

Result:

'The' is det of 'Marlins'
'Marlins' is nsubjpass of 'stymied'
'were' is auxpass of 'stymied'
'stymied' is ROOT of 'stymied'
'by' is agent of 'stymied'
'Austin' is compound of 'Gomber'
'Gomber' is pobj of 'by'
'and' is cc of 'Gomber'
'the' is det of 'Rockies'
'Rockies' is conj of 'Gomber'
'in' is prep of 'stymied'
'their' is poss of 'loss'
'4' is nummod of 'loss'
'-' is punct of '3'
'3' is prep of '4'
'loss' is pobj of 'in'
Related