Skip to content

Instantly share code, notes, and snippets.

@Abhayparashar31
Last active May 6, 2025 04:03
Show Gist options
  • Save Abhayparashar31/05e4d16d4e23550d77d2f33466ccd6bc to your computer and use it in GitHub Desktop.
Save Abhayparashar31/05e4d16d4e23550d77d2f33466ccd6bc to your computer and use it in GitHub Desktop.
import requests
import pandas as pd
# Load dataset (first 30 reviews)
url = "https://raw.githubusercontent.com/Abhayparashar31/NLPP_sentiment-analsis-on-hotel-review/refs/heads/main/Restaurant_Reviews.tsv"
df = pd.read_csv(url, sep='\t').head(30)
# API details
API_KEY = ""
API_URL = "https://api.apilayer.com/text_to_emotion"
headers = {"apikey": API_KEY}
# Function to get dominant emotion
def get_emotion(text):
response = requests.post(API_URL, headers=headers, data=text.encode("utf-8"))
if response.status_code == 200:
emotions = response.json()
return max(emotions, key=emotions.get) # Return the highest scoring emotion
return "Error"
# Apply API to each review
df["Emotion"] = df["Review"].apply(get_emotion)
# Function to apply color coding based on emotion
def highlight_emotion(row):
colors = {
"Angry": "background-color: red; color: white;",
"Happy": "background-color: green; color: white;",
"Fear": "background-color: brown; color: white;",
"Sad": "background-color: orange; color: black;",
"Surprise": "background-color: lightblue; color: black;"
}
return [colors.get(row["Emotion"], "")] * len(row)
# Style DataFrame
styled_df = df[["Review", "Emotion"]].style.apply(highlight_emotion, axis=1)
# Display DataFrame with styles
styled_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment