Sentiment Analysis of Generative AI using social media feeds¶

In [1]:
# ============================================================
# Text and Social Media Analytics Final Project Workflow
# Reddit + YouTube Generative AI Sentiment Analysis
# ============================================================

import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt

import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.sentiment import SentimentIntensityAnalyzer

from textblob import TextBlob
from wordcloud import WordCloud

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import csv

Load Datasets

In [2]:
# ------------------------------------------------------------
# 1. Load datasets
# ------------------------------------------------------------

reddit = pd.read_csv("C:/Users/bredd/PycharmProjects/PythonProject/PythonProject/PythonProject/PythonProject/reddit_ai_posts_cleaned.csv")
youtube = pd.read_csv("C:/Users/bredd/PycharmProjects/PythonProject/PythonProject/PythonProject/PythonProject/youtube_ai_sentiment.csv")

print("Reddit shape:", reddit.shape)
print("YouTube shape:", youtube.shape)


# ------------------------------------------------------------
# 2. Combine datasets
# ------------------------------------------------------------

common_cols = [
    "platform", "post_id", "comment_id", "subreddit", "title",
    "selftext", "text", "score", "comment_count", "like_count",
    "reply_count", "created_at", "permalink", "collection_method",
    "clean_text", "text_length", "month"
]

reddit = reddit[common_cols]
youtube = youtube[common_cols]

df = pd.concat([reddit, youtube], ignore_index=True)

print("Combined dataset shape:", df.shape)
print(df["platform"].value_counts())


# ------------------------------------------------------------
# 4. Text preprocessing
# ------------------------------------------------------------

nltk.download("stopwords")
nltk.download("wordnet")
nltk.download("vader_lexicon")
nltk.download("omw-1.4")

stop_words = set(stopwords.words("english"))

# keep important negation words
negation_words = {"no", "not", "nor", "never"}

stop_words = stop_words - negation_words

#check whether we should apply spellcheck before lemmatizer

# Identify words that would change via spellcheck


from textblob import TextBlob
from collections import Counter

def find_spellcheck_changes(
    text_series,
    min_frequency=3,
    min_word_length=4
):

    # Combine all text
    combined_text = " ".join(
        text_series.fillna("").astype(str)
    ).lower()

    # Extract words
    words = re.findall(r"\b[a-z]+\b", combined_text)

    # Count word frequencies
    word_counts = Counter(words)

    changes = []

    for word, count in word_counts.items():

        # Skip very short or infrequent words
        if len(word) < min_word_length:
            continue

        if count < min_frequency:
            continue

        corrected = str(TextBlob(word).correct())

        # Only keep words that would change
        if corrected != word:

            changes.append({
                "original_word": word,
                "suggested_correction": corrected,
                "frequency": count
            })

    changes_df = pd.DataFrame(changes)

    if not changes_df.empty:

        changes_df = changes_df.sort_values(
            by="frequency",
            ascending=False
        )

    return changes_df

spellcheck_changes = find_spellcheck_changes(
    df["clean_text"],
    min_frequency=3
)

print(spellcheck_changes.head(50).to_string(index=False))
Reddit shape: (6335, 17)
YouTube shape: (832, 17)
Combined dataset shape: (7167, 17)
platform
Reddit     6335
Youtube     832
Name: count, dtype: int64
[nltk_data] Downloading package stopwords to
[nltk_data]     C:\Users\bredd\AppData\Roaming\nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
[nltk_data] Downloading package wordnet to
[nltk_data]     C:\Users\bredd\AppData\Roaming\nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
[nltk_data] Downloading package vader_lexicon to
[nltk_data]     C:\Users\bredd\AppData\Roaming\nltk_data...
[nltk_data]   Package vader_lexicon is already up-to-date!
[nltk_data] Downloading package omw-1.4 to
[nltk_data]     C:\Users\bredd\AppData\Roaming\nltk_data...
[nltk_data]   Package omw-1.4 is already up-to-date!
original_word suggested_correction  frequency
      chatgpt               catgut       2997
       openai                 open       1164
        thats                 that        923
       doesnt                doesn        784
         cant                  can        769
        youre                 your        704
         isnt                  isn        691
       gemini               remind        572
       google                goose        531
        didnt                 didn        491
        whats                 what        474
       coding               coming        470
         llms                 alms        455
       theyre                there        435
      prompts               prompt        393
        heres                 here        390
       theres                there        381
         tech                teach        368
    anthropic           anthropoid        355
        codex                 code        276
         gpto                   to        253
      agentic               agents        234
       reddit               credit        232
         grok                 grow        232
        arent                agent        229
        wasnt                 want        227
       altman                altar        223
      openais                penis        179
        youve                  you        170
         hype                 hope        166
      outputs               output        165
       skills                skill        165
         guys                 guns        164
       videos                video        160
         apps                 apes        159
      chatbot              charcot        156
    generated             generate        154
   automation            automatic        151
   structured           structures        148
         math                 path        148
  researchers           researches        131
         meta                  met        129
   developers            developer        126
       havent                haven        125
      couldnt               couldn        125
         elon                elson        120
       emails                email        119
         weve                 were        118
      browser              brother        118
         opus                  pus        116
In [2]:
 

Given that it appears spellchecker would not provide meaningful gains we will continue pre-processing without spellcheck.

In [3]:
#Pre-processing continuing without spellcheck

#undertake lemmatization
lemmatiser = WordNetLemmatizer()

def preprocess_text(text):
    text = str(text).lower()
    text = re.sub(r"http\S+|www\S+", "", text)        # remove URLs
    text = re.sub(r"[^a-z\s]", "", text)              # keep letters only
    text = re.sub(r"\s+", " ", text).strip()          # remove extra spaces

    tokens = text.split()
    tokens = [
        lemmatiser.lemmatize(word)
        for word in tokens
        if word not in stop_words and len(word) > 2
    ]

    return " ".join(tokens)

df["processed_text"] = df["clean_text"].fillna(df["text"]).apply(preprocess_text)
df["processed_length"] = df["processed_text"].str.len()

# Remove any empty rows after preprocessing
df = df[df["processed_text"].str.len() > 0]

Topic/Theme Analysis

In [10]:
# Bag of N-Grams Analysis (bi- grams and tri-grams)

#tri-grams


ngram_vectoriser = CountVectorizer(
    stop_words="english",
    ngram_range=(3, 3),      # trigrams
    min_df=5,
    max_df=0.90
)

ngram_matrix = ngram_vectoriser.fit_transform(df["processed_text"])

ngram_counts = np.asarray(ngram_matrix.sum(axis=0)).flatten()

ngram_features = ngram_vectoriser.get_feature_names_out()

ngram_df = pd.DataFrame({
    "ngram": ngram_features,
    "count": ngram_counts
})

ngram_df = ngram_df.sort_values(
    by="count",
    ascending=False
)

print("\nTop tri-grams:")
print(ngram_df.head(20).to_string(index=False))

ngram_df.to_csv("summary_top_ngrams.csv", index=False)

#bi-grams

bigram_vectoriser = CountVectorizer(
    stop_words="english",
    ngram_range=(2, 2),      # bigrams
    min_df=5,
    max_df=0.90
)

bigram_matrix = bigram_vectoriser.fit_transform(df["processed_text"])

bigram_counts = np.asarray(bigram_matrix.sum(axis=0)).flatten()

bigram_features = bigram_vectoriser.get_feature_names_out()

bigram_df = pd.DataFrame({
    "ngram": bigram_features,
    "count": bigram_counts
})

bigram_df = bigram_df.sort_values(
    by="count",
    ascending=False
)

print("\nTop bi-grams:")
print(bigram_df.head(20).to_string(index=False))

bigram_df.to_csv("summary_top_bigrams.csv", index=False)



# TF-IDF keyword analysis

tfidf_vectoriser = TfidfVectorizer(
    max_df=0.90,
    min_df=5,
    stop_words="english",
    max_features=1000,
    ngram_range=(3, 3)
)

tfidf_matrix = tfidf_vectoriser.fit_transform(df["processed_text"])

feature_names = tfidf_vectoriser.get_feature_names_out()

# Average TF-IDF score for each term
tfidf_scores = np.asarray(tfidf_matrix.mean(axis=0)).flatten()

tfidf_df = pd.DataFrame({
    "term": feature_names,
    "tfidf_score": tfidf_scores
}).sort_values(by="tfidf_score", ascending=False)

print("\nTop TF-IDF terms:")
print(tfidf_df.head(30))

tfidf_df.to_csv("summary_tfidf_terms.csv", index=False)


# Topic modelling using LDA


vectoriser = CountVectorizer(
    max_df=0.90,
    min_df=5,
    stop_words="english",
    max_features=1000,
    ngram_range=(1,2)
)

dtm = vectoriser.fit_transform(df["processed_text"])

lda = LatentDirichletAllocation(
    n_components=5,
    random_state=42,
    learning_method="batch"
)

lda.fit(dtm)

feature_names = vectoriser.get_feature_names_out()

def display_topics(model, feature_names, no_top_words=10):
    topics = []

    for topic_idx, topic in enumerate(model.components_):
        top_words = [
            feature_names[i]
            for i in topic.argsort()[:-no_top_words - 1:-1]
        ]
        topics.append({
            "topic_number": topic_idx + 1,
            "top_words": ", ".join(top_words)
        })

    return pd.DataFrame(topics)

topics_df = display_topics(lda, feature_names, 10)
pd.set_option('display.max_colwidth', None)

print("\nLDA Topics:")
print(topics_df)

topics_df.to_csv("lda_topics.csv", index=False)

# Assign dominant topic to each record
topic_values = lda.transform(dtm)
df["dominant_topic"] = topic_values.argmax(axis=1) + 1
Top tri-grams:
                          ngram  count
           large language model     45
              ive using chatgpt     25
          chatgpt claude gemini     25
            standard voice mode     17
               white collar job     15
               free open source     14
            advanced voice mode     13
                 ceo sam altman     13
          happy answer question     13
             people use chatgpt     13
               people dont know     12
         youre absolutely right     12
           curious people think     11
artificial general intelligence     11
              dont think people     11
                 feel like real     11
          prompt included hello     11
            people actually use     11
     prompt variable definition     11
             honestly feel like     11

Top bi-grams:
                  ngram  count
              feel like    512
              look like    214
              dont know    204
               use case    164
            claude code    158
            use chatgpt    154
               chat gpt    145
             sam altman    143
              dont want    142
            chatgpt pro    142
          using chatgpt    136
artificial intelligence    125
          deep research    118
                gpt pro    114
               year ago    112
            open source    112
           chatgpt plus    106
             dont think    103
            data center    100
               ive seen    100

Top TF-IDF terms:
                         term  tfidf_score
96       large language model     0.004773
93          ive using chatgpt     0.002706
23      chatgpt claude gemini     0.002644
83      happy answer question     0.001626
136        people use chatgpt     0.001571
74           free open source     0.001494
43       curious people think     0.001399
21             ceo sam altman     0.001316
188            using chat gpt     0.001313
1          actually look like     0.001309
131          people dont know     0.001308
68             feel like real     0.001301
162       standard voice mode     0.001299
45      didnt know difference     0.001256
12         asked chatgpt make     0.001256
201          white collar job     0.001253
53          dont think people     0.001242
49      dont fully understand     0.001232
47          doesnt make sense     0.001220
87         honestly feel like     0.001192
27   chatgpt pro subscription     0.001154
22               chat gpt pro     0.001151
128       people actually use     0.001126
125         open source model     0.001117
156            sam altman say     0.001079
92           ive thinking lot     0.001074
133    people dont understand     0.001070
205    youre absolutely right     0.001062
119           nano banana pro     0.001058
64          feel like chatgpt     0.001053

LDA Topics:
   topic_number  \
0             1   
1             2   
2             3   
3             4   
4             5   

                                                                             top_words  
0                model, agent, llm, data, code, claude, actually, real, problem, layer  
1                       gpt, like, chatgpt, model, chat, feel, time, pro, answer, dont  
2                 chatgpt, use, tool, prompt, using, work, like, claude, project, help  
3  human, user, openai, prompt, emotional, step, new, anthropic, safety, consciousness  
4                       people, like, think, human, dont, thing, make, year, work, job  

Sentiment Analysis

In [5]:
# Sentiment Analysis using VADER

sia = SentimentIntensityAnalyzer()

df["vader_compound"] = df["processed_text"].apply(
    lambda x: sia.polarity_scores(x)["compound"]
)

def classify_vader(score):
    if score >= 0.05:
        return "Positive"
    elif score <= -0.05:
        return "Negative"
    else:
        return "Neutral"

df["vader_sentiment"] = df["vader_compound"].apply(classify_vader)


# Sentiment analysis using TextBlob


df["textblob_polarity"] = df["processed_text"].apply(
    lambda x: TextBlob(x).sentiment.polarity
)

def classify_textblob(score):
    if score >= 0.05:
        return "Positive"
    elif score <= -0.05:
        return "Negative"
    else:
        return "Neutral"

df["textblob_sentiment"] = df["textblob_polarity"].apply(classify_textblob)

vader_counts = (
    df["vader_sentiment"]
    .value_counts()
    .reset_index()
)

vader_counts.columns = [
    "VADER sentiment",
    "count"
]

print(vader_counts.to_string(index=False))

# Compare VADER vs TextBlob sentiment results


# Agreement / disagreement between models
df["sentiment_agreement"] = np.where(
    df["vader_sentiment"] == df["textblob_sentiment"],
    "Agree",
    "Disagree"
)

agreement_rate = (
    df["sentiment_agreement"]
    .value_counts(normalize=True)
    .mul(100)
    .round(2)
)

print("\nVADER vs TextBlob agreement rate:")
print(agreement_rate)

# Confusion-style comparison table
sentiment_comparison = pd.crosstab(
    df["vader_sentiment"],
    df["textblob_sentiment"],
    rownames=["VADER"],
    colnames=["TextBlob"]
)

print("\nVADER vs TextBlob sentiment comparison:")
print(sentiment_comparison)
VADER sentiment  count
       Positive   3945
       Negative   1814
        Neutral   1406

VADER vs TextBlob agreement rate:
sentiment_agreement
Agree       58.44
Disagree    41.56
Name: proportion, dtype: float64

VADER vs TextBlob sentiment comparison:
TextBlob  Negative  Neutral  Positive
VADER                                
Negative       592      797       425
Neutral        139      984       283
Positive       301     1033      2611

Time-Series Analysis

In [22]:
# bi grams by month

#create a heatmap showing bi-grams by month

monthly_bigram_results = []

months = sorted(df["month"].unique())

for month in months:

    month_df = df[df["month"] == month]

    # Skip very small datasets
    if len(month_df) < 5:
        continue

    bigram_vectoriser = CountVectorizer(
        stop_words="english",
        ngram_range=(2, 2),
        min_df=2,
        max_df=0.90
    )

    bigram_matrix = bigram_vectoriser.fit_transform(
        month_df["processed_text"]
    )

    bigram_counts = np.asarray(
        bigram_matrix.sum(axis=0)
    ).flatten()

    bigram_features = (
        bigram_vectoriser.get_feature_names_out()
    )

    month_bigram_df = pd.DataFrame({
        "month": month,
        "ngram": bigram_features,
        "count": bigram_counts
    })

    month_bigram_df = month_bigram_df.sort_values(
        by="count",
        ascending=False
    )

    # Keep top 5 per month
    top_bigrams = month_bigram_df.head(5)

    monthly_bigram_results.append(top_bigrams)

# Combine all months
monthly_bigram_df = pd.concat(
    monthly_bigram_results,
    ignore_index=True
)

# Add rank within each month
monthly_bigram_df["rank"] = (
    monthly_bigram_df
    .groupby("month")["count"]
    .rank(method="first", ascending=False)
    .astype(int)
)

# Reorder columns
monthly_bigram_clean = monthly_bigram_df[
    ["month", "rank", "ngram", "count"]
].sort_values(["month", "rank"])

print(monthly_bigram_clean.to_string(index=False))

monthly_bigram_clean.to_csv(
    "monthly_bigram_ranked.csv",
    index=False
)




#TF-IDF by month

# Convert monthly TF-IDF results to wide format

from sklearn.feature_extraction.text import TfidfVectorizer

monthly_tfidf_results = []

months = sorted(df["month"].unique())

for month in months:

    month_df = df[df["month"] == month]

    if len(month_df) < 5:
        continue

    tfidf_vectoriser = TfidfVectorizer(
        stop_words="english",
        max_features=1000,
        min_df=2,
        max_df=0.90,
        ngram_range=(1, 2)
    )

    tfidf_matrix = tfidf_vectoriser.fit_transform(
        month_df["processed_text"]
    )

    feature_names = tfidf_vectoriser.get_feature_names_out()

    tfidf_scores = np.asarray(
        tfidf_matrix.mean(axis=0)
    ).flatten()

    month_tfidf_df = pd.DataFrame({
        "month": month,
        "term": feature_names,
        "tfidf_score": tfidf_scores
    })

    month_tfidf_df = month_tfidf_df.sort_values(
        by="tfidf_score",
        ascending=False
    )

    top_terms = month_tfidf_df.head(5)

    monthly_tfidf_results.append(top_terms)

# THIS creates monthly_tfidf_df
monthly_tfidf_df = pd.concat(
    monthly_tfidf_results,
    ignore_index=True
)

monthly_tables = []

months = sorted(monthly_tfidf_df["month"].unique())

for month in months:

    month_subset = (
        monthly_tfidf_df[
            monthly_tfidf_df["month"] == month
        ][["term", "tfidf_score"]]
        .reset_index(drop=True)
    )

    # Rename columns
    month_subset.columns = [
        f"{month}_term",
        f"{month}_tfidf_score"
    ]

    monthly_tables.append(month_subset)

# Combine side-by-side
monthly_tfidf_wide = pd.concat(
    monthly_tables,
    axis=1
)

pd.set_option("display.max_columns", None)
pd.set_option("display.width", None)
pd.set_option("display.max_colwidth", None)
print(monthly_tfidf_wide)

monthly_tfidf_wide.to_csv(
    "monthly_tfidf_wide.csv",
    index=False
)


# Average monthly sentiment (VADER) scores with sample size


combined_monthly = (
    df.groupby("month")
    .agg(
        average_sentiment=("vader_compound", "mean"),
        record_count=("vader_compound", "count")
    )
    .reset_index()
)

print(combined_monthly)



# Export comparison tables
sentiment_comparison.to_csv("summary_vader_vs_textblob_comparison.csv")
score_comparison.to_csv("summary_vader_textblob_scores_by_platform.csv")
  month  rank          ngram  count
2025-05     1      dont know      7
2025-05     2      dont want      6
2025-05     3       use case      4
2025-05     4      feel like      4
2025-05     5   roughly word      4
2025-06     1      feel like     26
2025-06     2       chat gpt     22
2025-06     3      dont know     17
2025-06     4  using chatgpt     15
2025-06     5   chatgpt plus     15
2025-07     1  deep research     20
2025-07     2      dont know     19
2025-07     3      feel like     18
2025-07     4       chat gpt     18
2025-07     5  using chatgpt     17
2025-08     1      feel like     66
2025-08     2 standard voice     28
2025-08     3     voice mode     27
2025-08     4      dont want     25
2025-08     5     sam altman     23
2025-09     1      feel like     27
2025-09     2    use chatgpt     17
2025-09     3 standard voice     16
2025-09     4      dont want     12
2025-09     5      dont know     11
2025-10     1      feel like     25
2025-10     2      look like     14
2025-10     3     sam altman     13
2025-10     4    chatgpt pro     11
2025-10     5     adult mode     11
2025-11     1      feel like     22
2025-11     2       use case     17
2025-11     3        gpt pro     15
2025-11     4     sam altman     12
2025-11     5  super helpful     12
2025-12     1      feel like     28
2025-12     2      dont know     16
2025-12     3    data center     15
2025-12     4     sam altman     11
2025-12     5        gpt pro     11
2026-01     1      feel like     30
2026-01     2    open source     17
2026-01     3      look like     15
2026-01     4    chatgpt pro     15
2026-01     5    use chatgpt     12
2026-02     1      feel like     39
2026-02     2    chatgpt pro     16
2026-02     3       chat gpt     15
2026-02     4       year ago     15
2026-02     5     sam altman     15
2026-03     1    claude code     25
2026-03     2      feel like     25
2026-03     3      look like     16
2026-03     4      new model     15
2026-03     5       use case     14
2026-04     1      feel like     40
2026-04     2    chatgpt pro     23
2026-04     3    claude code     21
2026-04     4        gpt pro     19
2026-04     5    use chatgpt     15
2026-05     1      feel like    162
2026-05     2      look like     82
2026-05     3      dont know     58
2026-05     4    claude code     54
2026-05     5       use case     53
  2025-05_term  2025-05_tfidf_score 2025-06_term  2025-06_tfidf_score  \
0         like             0.034829      chatgpt             0.059094   
1          say             0.034521         like             0.034619   
2       people             0.033018        model             0.028841   
3      chatgpt             0.032326        human             0.027117   
4      thought             0.031916       people             0.025646   

  2025-07_term  2025-07_tfidf_score 2025-08_term  2025-08_tfidf_score  \
0      chatgpt             0.052407          gpt             0.067692   
1         like             0.028308      chatgpt             0.050072   
2         grok             0.025954       people             0.036251   
3        video             0.024253        model             0.034115   
4          gpt             0.023225         like             0.033425   

  2025-09_term  2025-09_tfidf_score 2025-10_term  2025-10_tfidf_score  \
0      chatgpt             0.045453      chatgpt             0.042980   
1         like             0.036361        video             0.029333   
2       people             0.029999         like             0.028678   
3       openai             0.028007       people             0.026235   
4          gpt             0.027367       openai             0.024152   

  2025-11_term  2025-11_tfidf_score 2025-12_term  2025-12_tfidf_score  \
0      chatgpt             0.038888      chatgpt             0.038082   
1         like             0.032541       people             0.035716   
2       openai             0.021510         like             0.033791   
3   difference             0.020760        model             0.027887   
4        model             0.020441          gpt             0.023831   

  2026-01_term  2026-01_tfidf_score 2026-02_term  2026-02_tfidf_score  \
0         like             0.034777      chatgpt             0.042502   
1      chatgpt             0.034756         like             0.030079   
2          art             0.031731       people             0.028196   
3       people             0.029743        model             0.027707   
4        human             0.029027       openai             0.023503   

  2026-03_term  2026-03_tfidf_score 2026-04_term  2026-04_tfidf_score  \
0      chatgpt             0.043468          pro             0.035128   
1         like             0.028040      chatgpt             0.032731   
2       claude             0.026599         like             0.030652   
3       openai             0.025037          gpt             0.026339   
4        video             0.025025       people             0.024697   

  2026-05_term  2026-05_tfidf_score  
0      chatgpt             0.043690  
1         like             0.028366  
2        agent             0.025926  
3        model             0.025782  
4       people             0.021307  
      month  average_sentiment  record_count
0   2025-05           0.270849            79
1   2025-06           0.283291           399
2   2025-07           0.251024           417
3   2025-08           0.224285           622
4   2025-09           0.214586           384
5   2025-10           0.210819           361
6   2025-11           0.238220           499
7   2025-12           0.182454           366
8   2026-01           0.163947           430
9   2026-02           0.212408           492
10  2026-03           0.230338           525
11  2026-04           0.212888           466
12  2026-05           0.250304          2125

Cross Platform Comparison

In [11]:
# Cross Platform Comparison

#Sentiment
# Average Sentiment scores by platform (Textblob v Vader)
score_comparison = df.groupby("platform")[[
    "vader_compound",
    "textblob_polarity"
]].mean().round(3)

print("\nAverage sentiment scores by platform:")
print(score_comparison)


platform_sentiment = pd.crosstab(
    df["platform"],
    df["vader_sentiment"],
    normalize="index"
) * 100

print("\nVADER sentiment by platform:")
print(platform_sentiment.round(2))

monthly_sentiment = df.groupby(["month", "platform"])["vader_compound"].mean().reset_index()

sentiment_counts = df.groupby(
    ["platform", "vader_sentiment"]
).size().reset_index(name="count")

# ------------------------------------------------------------
# Percentage sentiment distribution by platform - unweighted
# ------------------------------------------------------------

sentiment_percent = pd.crosstab(
    df["platform"],
    df["vader_sentiment"],
    normalize="index"
) * 100

print(sentiment_percent)

sentiment_percent = sentiment_percent[
    ["Negative", "Neutral", "Positive"]
]

sentiment_percent.plot(
    kind="bar",
    figsize=(8, 5)
)

plt.title("Percentage Distribution of Sentiment by Platform")
plt.xlabel("Platform")
plt.ylabel("Percentage of Responses")
plt.xticks(rotation=0)

plt.legend(title="Sentiment")

plt.tight_layout()
plt.savefig(
    "visual_percentage_sentiment_distribution.png",
    dpi=300
)

plt.show()


# Engagement-weighted sentiment distribution by platform

df["sentiment_weight"] = np.where(
    df["platform"].str.lower() == "reddit",
    df["comment_count"],
    df["like_count"]
)

# Replace missing weights with 0
df["sentiment_weight"] = df["sentiment_weight"].fillna(0)

weighted_sentiment = (
    df.groupby(["platform", "vader_sentiment"])["sentiment_weight"]
    .sum()
    .reset_index()
)

weighted_sentiment["weighted_percent"] = (
    weighted_sentiment.groupby("platform")["sentiment_weight"]
    .transform(lambda x: x / x.sum() * 100)
)

weighted_sentiment_percent = weighted_sentiment.pivot(
    index="platform",
    columns="vader_sentiment",
    values="weighted_percent"
)

weighted_sentiment_percent = weighted_sentiment_percent[
    ["Negative", "Neutral", "Positive"]
]

print(weighted_sentiment_percent.round(2))

weighted_sentiment_percent.plot(
    kind="bar",
    figsize=(8, 5)
)

plt.title("Engagement-Weighted Sentiment Distribution by Platform")
plt.xlabel("Platform")
plt.ylabel("Percentage of Weighted Engagement")
plt.xticks(rotation=0)
plt.legend(title="Sentiment")

plt.tight_layout()
plt.savefig(
    "visual_weighted_sentiment_distribution.png",
    dpi=300
)

plt.show()
Average sentiment scores by platform:
          vader_compound  textblob_polarity
platform                                   
Reddit             0.225              0.055
Youtube            0.272              0.151

VADER sentiment by platform:
vader_sentiment  Negative  Neutral  Positive
platform                                    
Reddit              26.30    19.27     54.43
Youtube             17.83    22.29     59.88
vader_sentiment   Negative    Neutral   Positive
platform                                        
Reddit           26.298343  19.273875  54.427782
Youtube          17.831325  22.289157  59.879518
No description has been provided for this image
vader_sentiment  Negative  Neutral  Positive
platform                                    
Reddit              24.43    16.82     58.75
Youtube              6.28    23.71     70.01
No description has been provided for this image

Visualisations - Theme/Topic Analysis

In [12]:
# Top TF-IDF terms

top_tfidf = tfidf_df.head(20).sort_values("tfidf_score")

plt.figure(figsize=(9, 6))
plt.barh(top_tfidf["term"], top_tfidf["tfidf_score"])
plt.title("Top TF-IDF Terms in Generative AI Discussion")
plt.xlabel("Average TF-IDF Score")
plt.ylabel("Term")
plt.tight_layout()
plt.savefig("visual10_top_tfidf_terms.png", dpi=300)
plt.show()

# Word cloud

all_text = " ".join(df["processed_text"])

wordcloud = WordCloud(
    width=1200,
    height=600,
    background_color="white"
).generate(all_text)

plt.figure(figsize=(12, 6))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.title("Most Common Terms in Reddit and YouTube AI Discussions")
plt.tight_layout()
plt.savefig("visual4_wordcloud.png", dpi=300)
plt.show()


# Top N-Grams

top_ngrams = (
    ngram_df.head(15)
    .sort_values(by="count")
)

plt.figure(figsize=(10, 6))

plt.barh(
    top_ngrams["ngram"],
    top_ngrams["count"]
)

plt.title("Most Common AI-Related N-Grams")
plt.xlabel("Frequency")
plt.ylabel("N-Gram")
plt.tight_layout()

plt.savefig("visual11_top_ngrams.png", dpi=300)
plt.show()


# Topic distribution


topic_counts = df.groupby(["platform", "dominant_topic"]).size().unstack(fill_value=0)

topic_counts.plot(kind="bar", figsize=(9, 5))
plt.title("Dominant Topic Distribution by Platform")
plt.xlabel("Platform")
plt.ylabel("Number of Records")
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig("visual5_topic_distribution.png", dpi=300)
plt.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

Visualisations - Sentiment Analysis

In [13]:
# Data volume by platform


plt.figure(figsize=(7, 5))
df["platform"].value_counts().plot(kind="bar")
plt.title("Number of Records by Platform")
plt.xlabel("Platform")
plt.ylabel("Number of Records")
plt.tight_layout()
plt.savefig("visual1_records_by_platform.png", dpi=300)
plt.show()



# ------------------------------------------------------------
# Visualisation: VADER vs TextBlob sentiment category counts
# ------------------------------------------------------------

sentiment_order = ["Negative", "Neutral", "Positive"]

vader_counts = df["vader_sentiment"].value_counts()
textblob_counts = df["textblob_sentiment"].value_counts()

sentiment_method_counts = pd.DataFrame({
    "VADER": vader_counts,
    "TextBlob": textblob_counts
}).reindex(sentiment_order).fillna(0)

sentiment_method_counts.plot(kind="bar", figsize=(8, 5))

plt.title("VADER vs TextBlob Sentiment Classifications")
plt.xlabel("Sentiment Category")
plt.ylabel("Number of Records")
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig("visual7_vader_vs_textblob_classification.png", dpi=300)
plt.show()


# Agreement vs disagreement - Textblob v VADER


df["sentiment_agreement"].value_counts().plot(kind="bar", figsize=(6, 5))

plt.title("Agreement Between VADER and TextBlob Sentiment Results")
plt.xlabel("Agreement Status")
plt.ylabel("Number of Records")
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig("visual8_vader_textblob_agreement.png", dpi=300)
plt.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

Visualisations: Time Series Analysis

In [23]:
# Monthly sentiment trend


# Sentiment trend across Reddit + YouTube - using VADER


combined_monthly_sentiment = (
    df.groupby("month")["vader_compound"]
    .mean()
    .reset_index()
)

plt.figure(figsize=(10, 5))

plt.plot(
    combined_monthly_sentiment["month"],
    combined_monthly_sentiment["vader_compound"],
    marker="o"
)

plt.title("Combined Average Monthly Sentiment Toward Generative AI")
plt.xlabel("Month")
plt.ylabel("Average VADER Compound Score")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig("visual_combined_monthly_sentiment.png", dpi=300)
plt.show()


# tri-grams heatmap

# Keep top 5 per month
monthly_bigram_top5 = monthly_bigram_clean[
    monthly_bigram_clean["rank"] <= 5
]

# Pivot for heatmap
bigram_heatmap = monthly_bigram_top5.pivot_table(
    index="ngram",
    columns="month",
    values="count",
    fill_value=0
)

plt.figure(figsize=(12, 8))

plt.imshow(bigram_heatmap, aspect="auto")

plt.xticks(
    range(len(bigram_heatmap.columns)),
    bigram_heatmap.columns,
    rotation=45
)

plt.yticks(
    range(len(bigram_heatmap.index)),
    bigram_heatmap.index
)

plt.colorbar(label="Frequency")

plt.title("Top Monthly Bigrams in Generative AI Discussion")
plt.xlabel("Month")
plt.ylabel("Bigram")

plt.tight_layout()
plt.savefig("visual_monthly_bigram_heatmap.png", dpi=300)
plt.show()
No description has been provided for this image
No description has been provided for this image

Cross Platform Analysis

In [15]:
# Sentiment distribution by platform

sentiment_plot = pd.crosstab(df["platform"], df["vader_sentiment"])

sentiment_plot.plot(kind="bar", figsize=(8, 5))
plt.title("Sentiment Distribution (VADER) by Platform")
plt.xlabel("Platform")
plt.ylabel("No. of Records")
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig("visual2_sentiment_distribution.png", dpi=300)
plt.show()



# Average VADER vs TextBlob score by platform

score_comparison.plot(kind="bar", figsize=(8, 5))

plt.title("Average Sentiment Scores by Platform: VADER vs TextBlob")
plt.xlabel("Platform")
plt.ylabel("Average Sentiment Score")
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig("visual9_average_scores_vader_textblob.png", dpi=300)
plt.show()

plt.figure(figsize=(10, 5))

for platform in monthly_sentiment["platform"].unique():
    subset = monthly_sentiment[monthly_sentiment["platform"] == platform]
    plt.plot(subset["month"], subset["vader_compound"], marker="o", label=platform)

plt.title("Average Monthly Sentiment Toward Generative AI")
plt.xlabel("Month")
plt.ylabel("Average VADER Compound Score")
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.savefig("visual3_monthly_sentiment_trend.png", dpi=300)
plt.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
In [ ]:
# ------------------------------------------------------------
# 15. Export final combined dataset and summaries
# ------------------------------------------------------------

df.to_csv("combined_ai_sentiment_analysis.csv", index=False)
platform_sentiment.to_csv("summary_platform_sentiment.csv")
monthly_sentiment.to_csv("summary_monthly_sentiment.csv", index=False)
sentiment_counts.to_csv("summary_sentiment_counts.csv", index=False)
topic_counts.to_csv("summary_topic_counts.csv")


print("\nWorkflow complete.")
print("Files exported:")
print("- summary_tfidf_terms.csv")
print(" - visual11_top_ngrams.png")
print("- visual10_top_tfidf_terms.png")

print("- combined_ai_sentiment_analysis.csv")
print("- lda_topics.csv")
print("- summary_platform_sentiment.csv")
print("- summary_monthly_sentiment.csv")
print("- summary_sentiment_counts.csv")
print("- summary_vader_vs_textblob_comparison.csv")
print("- summary_vader_textblob_scores_by_platform.csv")
print("- visual7_vader_vs_textblob_classification.png")
print("- visual8_vader_textblob_agreement.png")
print("- visual9_average_scores_vader_textblob.png")
print("- summary_topic_counts.csv")
print("- visual1_records_by_platform.png")
print("- visual2_sentiment_distribution.png")
print("- visual3_monthly_sentiment_trend.png")
print("visual_combined_monthly_sentiment.png")
print("- visual4_wordcloud.png")
print("- visual5_topic_distribution.png")
print("- visual_percentage_sentiment_distribution.png")
In [ ]: