Spaces:
Sleeping
Sleeping
File size: 1,608 Bytes
706ec74 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import pandas as pd
from textblob import TextBlob
def analyze_sentiment(text):
"""Perform sentiment analysis on the given text."""
try:
blob = TextBlob(text)
polarity = blob.sentiment.polarity
if polarity > 0:
sentiment = "Positive"
elif polarity < 0:
sentiment = "Negative"
else:
sentiment = "Neutral"
return sentiment, round(polarity, 2)
except Exception as e:
print(f"Error in sentiment analysis: {e}")
return "Neutral", 0.0
def perform_sentiment_analysis(csv_file):
"""Analyze sentiment for all articles in the CSV."""
df = pd.read_csv(csv_file)
if 'summary' not in df.columns:
print("No 'summary' column found in CSV.")
return None
df['sentiment'], df['polarity'] = zip(*df['summary'].apply(analyze_sentiment))
# Save the result with sentiment analysis
output_csv = csv_file.replace('.csv', '_sentiment.csv')
df.to_csv(output_csv, index=False)
print(f"β
Sentiment analysis saved to {output_csv}")
return df
def comparative_analysis(df):
"""Perform comparative sentiment analysis across multiple articles."""
sentiment_counts = df['sentiment'].value_counts(normalize=True) * 100
print("\nπ Sentiment Distribution:")
print(sentiment_counts)
summary = {
"positive": sentiment_counts.get("Positive", 0),
"negative": sentiment_counts.get("Negative", 0),
"neutral": sentiment_counts.get("Neutral", 0)
}
return summary
|