Extract Nouns Using Flair NER Model

  • Share this:

Code introduction


This function uses a pre-trained model from the Flair library to perform named entity recognition (NER) on the provided text and extracts nouns from it.


Technology Stack : Flair, TextClassifier, Sentence

Code Type : Text processing

Code Difficulty : Intermediate


                
                    
def extract_nouns_from_text(text, language='en'):
    import flair
    from flair.models import TextClassifier
    from flair.data import Sentence

    # Load a pre-trained NER model for English
    model = TextClassifier.load('en-ner-coref')

    # Create a sentence object of the provided text
    sentence = Sentence(text)

    # Perform named entity recognition
    model.predict(sentence)

    # Extract all nouns
    nouns = [token for token in sentence if token.tag == 'NN' or token.tag == 'NNS']

    # Return a list of nouns
    return [token.text for token in nouns]