EXERCISE 6.1: SENTIMENT ANALYSIS

Objective: Write a Python script to perform sentiment analysis on the provided social media posts.

Tasks:

  1. Load the “sentiment_analysis_data.csv” into a Python program.
  2. Use a sentiment analysis library TextBlob to analyze the sentiment of each post.
  3. Categorize each post as ‘Positive’, ‘Negative’, or ‘Neutral’ based on the sentiment score.
  4. Output the sentiment analysis results in a readable format.

Steps:

  1. Load the Data:
    • First, import necessary libraries and read the CSV file containing the sentiment data.
    1. import pandas as pd
    2. sentiment_df = pd.read_csv('path_to_csv_file')
  2. Install and Import TextBlob:
    • Install TextBlob, if not already installed, using !pip install textblob.
    • Import TextBlob for sentiment analysis.
    3. !pip install textblob
    4. from textblob import TextBlob
  3. Perform Sentiment Analysis:
    • Define a function to analyze sentiment using TextBlob.
    • Apply this function to each post in the dataset.
    5. def analyze_sentiment(post):
    6. analysis = TextBlob(post)
    7. return 'Positive' if analysis.sentiment.polarity> 0 else 'Negative' if analysis.sentiment.polarity < 0 else 'Neutral'
    8. sentiment_df['Analyzed_Sentiment'] = sentiment_df['Post'].apply(analyze_sentiment)
  4. Display the Results:
    • Show the first few rows of the DataFrame with the original posts and their analyzed sentiments.
    9. sentiment_df.head()

This code provides a step-by-step approach to performing sentiment analysis on text data using Python and the TextBlob library. Each ...

Get Mastering Marketing Data Science now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.