CommencerCommencer gratuitement

Setting extension attributes (2)

Let's try setting some more complex attributes using getters and method extensions. The nlp object has already been created for you and the Doc, Token and Span classes are already imported.

Remember that if you run your code more than once, you might see an error message that the extension already exists. That's because DataCamp will re-run your code in the same session. To solve this, you can set force=True on set_extension, or reload to start a new Python session. None of this will affect the answer you submit.

Cet exercice fait partie du cours

Advanced NLP with spaCy

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Define the getter function
def get_has_number(doc):
    # Return if any of the tokens in the doc return True for token.like_num
    return any(____ for token in doc)

# Register the Doc property extension 'has_number' with the getter get_has_number
____.____(____, ____=____)

# Process the text and check the custom has_number attribute 
doc = nlp("The museum closed for five years in 2012.")
print('has_number:', ____)
Modifier et exécuter le code