Measure sentiment polarity of sentences and documents with spaCy
spacy-polarity is a spaCy pipeline component that adds sentiment polarity analysis to your pipeline. It supports both TextBlob-based polarity scoring and transformer-based sentiment analysis.
Install spacy-polarity via pip:
pip install spacy-polarityYou’ll also need a spaCy language model (e.g., en_core_web_sm):
python -m spacy download en_core_web_smFor transformer support, ensure you have transformers installed:
pip install "spacy-polarity[transformers]" Analyze sentiment polarity with TextBlob’s lightweight algorithm:
import spacy
import spacy_polarity
# Load spaCy model and add the polarity component
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("spacy_polarity")
# Process text
doc = nlp("The financial markets are performing well, bringing good returns to investors. The stock markets in USA grew by 5% this year.")
# Polarity for each sentence
for sent in doc.sents:
print(f"Sentence: {sent.text}")
print(f"Polarity: {sent._.polarity:.3f}\n")
# Polarity for the entire document
print(f"Document Polarity: {doc._.polarity:.3f}")Leverage transformer models for more advanced sentiment analysis:
import spacy
import spacy_polarity
# Load spaCy model and add the polarity component with transformers
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("spacy_polarity", config={"use_transformer": True})
# Process text
doc = nlp("The financial markets are performing well, bringing good returns to investors. The stock markets in USA grew by 5% this year.")
# Polarity for each sentence
for sent in doc.sents:
print(f"Sentence: {sent.text}")
print(f"Polarity: {sent._.polarity:.3f}\n")
# Polarity for the entire document
print(f"Document Polarity: {doc._.polarity:.3f}")This package processes documents individually and does not batch inference across multiple documents. For high-volume analysis or GPU optimization, consider a custom solution using the transformers library directly.
Ensure code quality with ruff:
ruff check
ruff formatInstall test dependencies and run tests:
pip install ".[test]"
pytest -vvvFor ARM architectures (e.g., Raspberry Pi, Apple M1), use the following:
apt install python3-dev
pip install wheel
BLIS_ARCH="generic" pip install spacy --no-binary blis
pip install spacy-polarity