Skip to content

Instantly share code, notes, and snippets.

@graylan0
Created December 5, 2023 21:56
Show Gist options
  • Save graylan0/0c530075cbc22d05f1388947c059be5e to your computer and use it in GitHub Desktop.
Save graylan0/0c530075cbc22d05f1388947c059be5e to your computer and use it in GitHub Desktop.
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
from nltk import pos_tag, word_tokenize
from colour import Color
nltk.download('vader_lexicon')
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
def generate_color(sentiment_score, pos_tag):
"""
Generate a color based on sentiment score and part of speech.
Uses a gradient for sentiment and modifies the shade based on the part of speech.
"""
base_color = Color(hue=sentiment_score * 0.5 + 0.5, saturation=1, luminance=0.5)
# Modify the color based on part of speech
if pos_tag.startswith('NN'):
base_color.luminance *= 0.9 # Darken for nouns
elif pos_tag.startswith('VB'):
base_color.saturation *= 0.7 # Desaturate for verbs
# ... other parts of speech adjustments
return base_color.hex_l
def colorize_text(text):
sia = SentimentIntensityAnalyzer()
words = word_tokenize(text)
tagged_words = pos_tag(words)
colored_text = ""
for word, tag in tagged_words:
sentiment_score = sia.polarity_scores(word)['compound']
color = generate_color(sentiment_score, tag)
colored_word = f'<span style="color:{color}">{word}</span>'
colored_text += colored_word + ' '
return colored_text
# Example usage
sample_text = "The quick brown fox jumps over the lazy dog."
colorized = colorize_text(sample_text)
print(colorized)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment