Search code examples
pythonnlpspacy

Spacy Entity Recognition not printing


Could someone help me. I am having an issue with Spacy entity recognition

# import spacy
# define a language module
import spacy
nlp = spacy.load('en')

# create 5 garden path sentences
old_man = """The old man the boat."""
single_soldiers = """The complex houses married and single soldiers and their families."""
horse_raced = """The horse raced past the barn fell."""
florist_flowers = """The florist sent the flowers was pleased."""
sour_drink = """The sour drink from the ocean."""

# add all sentences to a list
garden_path_sentences = [old_man, single_soldiers, horse_raced, florist_flowers, sour_drink]

# loop through garden_path_sentences
# for each sentence
# tokenise the sentence 
# perform and print out entity recognition results 
# print new line before next iteration 
for sentence in garden_path_sentences:
    nlp_sentence = nlp(sentence)
    print([token.orth_ for token in nlp_sentence if not token.is_punct | token.is_space])
    print([(word, word.label_, word.label) for word in nlp_sentence.ents])
    print('\n')

The above code gives me the following output:

['The', 'old', 'man', 'the', 'boat']
[]


['The', 'complex', 'houses', 'married', 'and', 'single', 'soldiers', 'and', 'their', 'families']
[]


['The', 'horse', 'raced', 'past', 'the', 'barn', 'fell']
[]


['The', 'florist', 'sent', 'the', 'flowers', 'was', 'pleased']
[]


['The', 'sour', 'drink', 'from', 'the', 'ocean']
[]

why is the entity recognition not printing? Any help would be appreciated.


Solution

  • First of all , your sentences don't have any entities to recognize .

    Second , there are lot of mistakes in the code .

    I have changed the code and the utterance please have a check at it.

    # import spacy
    # define a language module
    import spacy
    nlp = spacy.load('en_core_web_sm')
    
    # create 5 garden path sentences
    old_man = "i live in the USA"
    single_soldiers = "The complex houses married and single soldiers and their families."
    horse_raced = "The horse raced past the barn fell."
    florist_flowers = "The florist sent the flowers was pleased."
    sour_drink = "The sour drink from the ocean."
    
    # add all sentences to a list
    garden_path_sentences = [old_man, single_soldiers, horse_raced, florist_flowers, sour_drink]
    
    # loop through garden_path_sentences
    # for each sentence
    # tokenise the sentence 
    # perform and print out entity recognition results 
    # print new line before next iteration 
    
    for sentence in garden_path_sentences:
        for i in nlp(sentence).ents:
            print("Entity : {} , Text {}".format(i.label_,i.text))
    

    Thank you.