Sentiment Detection with spaCy TextCategorizer

  • Share this:

Code introduction


This function uses the TextCategorizer from spaCy to detect the sentiment of the text, supporting three categories: positive, negative, and neutral.


Technology Stack : spaCy, TextCategorizer

Code Type : Function

Code Difficulty : Intermediate


                
                    
def detect_sentiment(text):
    # Import necessary libraries from spaCy
    import spacy
    from spacy.textcat import TextCategorizer
    
    # Load the English tokenizer, tagger, parser, NER, and word vectors
    nlp = spacy.load("en_core_web_sm")
    
    # Add a text classifier to the pipeline
    textcat = TextCategorizer(nlp)
    textcat.add_label("Positive")
    textcat.add_label("Negative")
    textcat.add_label("Neutral")
    nlp.add_pipe(textcat, last=True)
    
    # Process the text
    doc = nlp(text)
    
    # Predict the sentiment
    sentiment = doc.cats.get("Positive", 0) - doc.cats.get("Negative", 0) + doc.cats.get("Neutral", 0)
    
    # Return the sentiment score
    return sentiment