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.

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.

Article image: How do you find the parts of speech in a sentence using Python? (source: O'Reilly).