You can download this code by clicking the button below.
This code is now available for download.
This function uses spaCy's EntityRuler to create custom entity rules based on the provided text.
Technology Stack : spaCy, EntityRuler
Code Type : Function
Code Difficulty : Intermediate
import spacy
from spacy.lang.en import English
from spacy.pipeline import EntityRuler
def create_entity_rules(text):
"""
This function uses spaCy's EntityRuler to create custom entity rules based on the provided text.
"""
nlp = English()
ruler = EntityRuler(nlp)
# Extracting entities from the text
doc = nlp(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
# Creating rules based on the entities
rules = []
for entity in entities:
rule = {"pattern": entity[0], "label": entity[1]}
rules.append(rule)
# Adding rules to the EntityRuler
ruler.add_rules(rules)
return ruler
# Example usage:
text = "Apple Inc. is an American multinational technology company headquartered in Cupertino, California."
ruler = create_entity_rules(text)
print(ruler)