How do you find the parts of speech in a sentence using Python?
Learn how to use spaCy to parse a sentence to return the parts of speech (noun, verb, etc.) and dependencies.
How do we get the parts of speech of a sentence?
We will use a library for Python called spaCy
from spacy.en import English parser = English() print(parser)
We create a function that shows the parts of speech and dependencies.
See the explanations of the abbreviations and a list of dependencies. Note that in this file the dependencies start with the block that begins “acomp” and finishes with “xcomp.”
Also, dependencies are described in the Stanford typed dependencies manual.
def show_dep(text): tokens = parser(text) for token in tokens: print(" {:<8} : {:<5} : {:<7} : {}".format(token.orth_,token.pos_,token.dep_,token.head)) print(" {:<8} : {:<5} : {:<7} : {}".format("token","POS","dep.","head")) print("------------------------------------") show_dep("I drove home with joy.")
We can also get the most important word in the sentence, called the “head.”
def get_head_of_sentence(text): tokens = parser(text) for token in tokens: if token.head is token: return token return None get_head_of_sentence("I drove home with joy.")