Кажется, ваш код пытается сделать что-то более сложное, чем то, что вы описали в своем вопросе.Я пытался сделать то, что вы хотите сделать с помощью своего кода.Получение объекта / атрибута глагола "is" или "was" является лишь частью этого.
import spacy
from pprint import pprint
nlp = spacy.load('en')
text = "He was a genius. I really liked working with him. He is a dog owner. She is very kind to animals."
def get_pro_nsubj(token):
# get the (lowercased) subject pronoun if there is one
return [child.lower_ for child in token.children if child.dep_ == 'nsubj'][0]
list_of_responses = []
# a mapping of subject to object pronouns
subj_obj_pro_map = {'he': 'him',
'she': 'her'
}
for token in nlp(text):
if token.pos_ in ['NOUN', 'ADJ']:
if token.dep_ in ['attr', 'acomp'] and token.head.lower_ in ['is', 'was']:
# to test for lemma 'be' use token.head.lemma_ == 'be'
nsubj = get_pro_nsubj(token.head)
if nsubj in ['he', 'she']:
# get the text of each token in the constituent and join it all together
whole_constituent = ' '.join([t.text for t in token.subtree])
obj_pro = subj_obj_pro_map[nsubj] # convert subject to object pronoun
returning_phrase = 'Why do you think {} being {} helped the two of you get along?'.format(obj_pro, whole_constituent)
list_of_responses.append(returning_phrase)
pprint(list_of_responses)
Что выводит это:
['Why do you think him being a genius helped the two of you get along?',
'Why do you think him being a dog owner helped the two of you get along?',
'Why do you think her being very kind to animals helped the two of you get '
'along?']