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.

By Jonathan Mugan
April 18, 2017
How do you find the parts of speech in a sentence using Python? How do you find the parts of speech in a sentence using Python? (source: O'Reilly)

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.

Learn faster. Dig deeper. See farther.

Join the O'Reilly online learning platform. Get a free trial today and find answers on the fly, or master something new and useful.

Learn more
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.")

Exercise: Write down the lyrics to your favorite song and get the parts of speech of each word.


Exercise for later: view the parts of speech in the dependency visualizer displaCy.

Post topics: Intelligence matters: Artificial intelligence and algorithms
Post tags: Questions
Share: