You can download this code by clicking the button below.
This code is now available for download.
This function uses the NER model from the Flair library to randomly extract entities from the given text.
Technology Stack : Flair, SequenceTagger, Sentence
Code Type : Function
Code Difficulty : Intermediate
def random_entity_extraction(text, model='bert-base-uncased'):
"""
Extracts random entities from a given text using Flair's NER model.
"""
from flair.models import SequenceTagger
from flair.data import Sentence
# Load the NER model
nlp = SequenceTagger.load(model)
# Create a sentence from the input text
sentence = Sentence(text)
# Perform NER
nlp.predict(sentence)
# Randomly select an entity and return it
if len(sentence.get_tokens()) > 0:
tokens = sentence.get_tokens()
selected_token = tokens[random.randint(0, len(tokens) - 1)]
return f"{selected_token.text} ({selected_token.tag})"
else:
return "No entities found in the text."