Skip to content

Instantly share code, notes, and snippets.

@chiefastro
Last active November 30, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiefastro/3de1b8b5a9633d1c6c02ab287f4adb2c to your computer and use it in GitHub Desktop.
Save chiefastro/3de1b8b5a9633d1c6c02ab287f4adb2c to your computer and use it in GitHub Desktop.
Get parent verb polarity with spaCy
import typing as t
import spacy
# load pre-trained model pipeline
nlp = spacy.load('en_core_web_sm')
# sentence for grammar rules
text = """He does not eat meat, but he loves Beyond Burgers."""
# apply pipeline
doc = nlp(text)
def get_parent_verb(
token: spacy.tokens.Token
) -> t.Optional[t.Tuple[spacy.tokens.Token, int]]:
"""Get the parent verb of token, along with its polarity
(1 for positive, -1 for negative)"""
# loop through ancestors
polarity = 1
for a in token.ancestors:
if a.pos_ in {'VERB', 'ROOT'}:
# found the first parent verb
verb = a
# check if it's negated
for l in a.lefts:
if l.dep_ == 'neg':
polarity = -1
# return first parent verb found
return (verb, polarity)
return None
# hard code "Beyond" token
token = doc[9]
# get parent verb and polarity
get_parent_verb(token)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment