spaCy - Doc.set_extension Classmethod



This class method was introduced in version 2.0. It defines a custom attribute on the Doc. Once done, that attribute will become available via Doc._.

Arguments

The table below explains its arguments −

NAME TYPE DESCRIPTION
name Unicode This argument represents the name of the attribute to set by the extension. For example, ‘his_attr’ will be available as doc._.his_attr.
default - It is the optional default value of the attribute for the case when no getter or method is defined.
method callable It is used to set a custom method on the object. For example, doc._.compare(other_doc).
getter callable This attribute represents the getter function that will takes the object and will return an attribute value. It is mainly called when the user accesses the ._ attribute.
setter callable This attribute represents the Setter function that will take the Doc & a value and will modify the object. It is mainly called when the user writes to the Doc._ attribute.
Force bool It will forcefully overwrite an existing attribute.

Example

An example of Doc.set_extension classmethod is as follows −

import spacy
nlp_model = spacy.load("en_core_web_sm")
from spacy.tokens import Doc
city = lambda doc: any(city in doc.text for city in ("New York", "India", "USA"))
Doc.set_extension("has_city", getter=city, force = True)
doc = nlp_model("I like India")
doc._.has_city

Output

True
spacy_containers.htm
Advertisements