Counting nouns in a piece of text
In this exercise, we will write two functions, nouns()
and proper_nouns()
that will count the number of other nouns and proper nouns in a piece of text respectively.
These functions will take in a piece of text and generate a list containing the POS tags for each word. It will then return the number of proper nouns/other nouns that the text contains. We will use these functions in the next exercise to generate interesting insights about fake news.
The en_core_web_sm
model has already been loaded as nlp
in this exercise.
This exercise is part of the course
Feature Engineering for NLP in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
nlp = spacy.load('en_core_web_sm')
# Returns number of proper nouns
def proper_nouns(text, model=nlp):
# Create doc object
doc = model(text)
# Generate list of POS tags
pos = [token.pos_ for token in doc]
# Return number of proper nouns
return ____.____(____)
print(proper_nouns("Abdul, Bill and Cathy went to the market to buy apples.", nlp))