Flair NER Model Text Extraction

  • Share this:

Code introduction


This function uses a pre-trained model from the Flair library to perform Named Entity Recognition (NER) on a given text. The function takes the text and the name of the model as parameters and returns a list containing the entity text and its corresponding label.


Technology Stack : Flair, SequenceTagger, Sentence

Code Type : Function

Code Difficulty : Intermediate


                
                    
def extract_ner_from_text(text, model_name='bert-base-cased'):
    """
    Extract Named Entity Recognition (NER) from a given text using a pre-trained model from the Flair library.

    Parameters:
        text (str): The input text from which to extract NER.
        model_name (str): The name of the pre-trained model to use for NER. Default is 'bert-base-cased'.

    Returns:
        list: A list of tuples containing the entity text and its corresponding label.
    """
    import flair
    from flair.models import SequenceTagger
    from flair.data import Sentence

    # Load the pre-trained NER model
    model = SequenceTagger.load(model_name)

    # Create a sentence from the input text
    sentence = Sentence(text)

    # Perform NER
    model.predict(sentence)

    # Extract the named entities
    entities = [(token.text, token标签) for token in sentence]

    return entities