|
| 1 | +from wordcloud import WordCloud, STOPWORDS |
| 2 | +import csv |
| 3 | +import pandas as pd |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +from dotenv import load_dotenv |
| 6 | +import plotly.express as px |
| 7 | +import requests |
| 8 | +import os |
| 9 | + |
| 10 | +load_dotenv() |
| 11 | +cvs_file = "socialmediapostdata.csv" |
| 12 | +cvs_url_key = "CVS_URL" |
| 13 | + |
| 14 | +# welcome message |
| 15 | +print("Welcome to the Social Media Analyzer!") |
| 16 | +print("-" * 75) |
| 17 | +print("This program will analyze social media posts data and visualize the number of posts per author per day.") |
| 18 | +print("Please follow the instructions to enter the URL of the CSV file containing the social media posts data.") |
| 19 | +print("-" * 75) |
| 20 | + |
| 21 | +# prompt user for the URL of the CSV file if not use env default |
| 22 | +cvs_url = input( |
| 23 | + "Please enter the URL to the CSV file (or press Enter to use the default): ") or os.getenv(cvs_url_key) |
| 24 | + |
| 25 | +# Check if the CSV file exists, if not download it from the provided URL |
| 26 | +if not os.path.exists(cvs_file): |
| 27 | + response = requests.get(cvs_url) |
| 28 | + with open(cvs_file, "wb") as csv_file: |
| 29 | + csv_file.write(response.content) |
| 30 | + |
| 31 | +# Load the dataset using pandas as pd |
| 32 | +post_data = pd.read_csv(cvs_file, encoding='utf-8') |
| 33 | +print(post_data) |
| 34 | + |
| 35 | +# Clean the dataset by removing unnecessary columns using the drop method from pandas |
| 36 | +post_data = post_data.drop( |
| 37 | + ['country', 'id', 'language', 'latitude', 'longitude'], axis=1) |
| 38 | +# print(post_data) |
| 39 | + |
| 40 | +# calculate the daily number of posts created by each user using to_datetime method to convert the 'date_time' column to datetime format |
| 41 | +post_data['date_time'] = pd.to_datetime( |
| 42 | + post_data['date_time'], format='%d/%m/%Y %H:%M').dt.date |
| 43 | +print(post_data) |
| 44 | + |
| 45 | +# Calculate the daily number of posts created by each user |
| 46 | +content_counts = post_data.groupby(['author', 'date_time'])[ |
| 47 | + 'content'].count().reset_index(name='content_count') |
| 48 | +print(content_counts) |
| 49 | + |
| 50 | +# Show few rows of the content_counts DataFrame to verify the grouping and counting |
| 51 | +content_counts['date_time'] = pd.to_datetime(content_counts['date_time']) |
| 52 | + |
| 53 | +# Plot the number of posts per author per day calculated above using matplotlib.pyplot |
| 54 | +plt.figure(figsize=(12, 6)) |
| 55 | +for author in content_counts['author'].unique(): |
| 56 | + author_data = content_counts[content_counts['author'] == author] |
| 57 | + plt.plot(author_data['date_time'], |
| 58 | + author_data['content_count'], marker='o', label=author) |
| 59 | +plt.title('Number of Posts for Author per Day') |
| 60 | +plt.xlabel('Date') |
| 61 | +plt.ylabel('Number of Posts') |
| 62 | +plt.legend(title='Author') |
| 63 | +plt.tight_layout() |
| 64 | +plt.show() |
| 65 | + |
| 66 | +# Plot the number of posts per author per day using Plotly Express |
| 67 | +fig = px.line( |
| 68 | + content_counts, |
| 69 | + x='date_time', |
| 70 | + y='content_count', |
| 71 | + color='author', |
| 72 | + markers=True, |
| 73 | + labels={'content_count': 'Number of Posts', 'date_time': 'Date'}, |
| 74 | + title='Number of Posts per Author per Day') |
| 75 | +fig.show() |
| 76 | + |
| 77 | +# Filter the DataFrame prompt user for input author |
| 78 | +author_name = input( |
| 79 | + "Please enter the author name to filter (e.g., 'jimmyfallon'): ") |
| 80 | +author_data = content_counts[content_counts['author'] == author_name].copy() |
| 81 | + |
| 82 | +# Ensure that 'date_time' is in datetime format for plotting |
| 83 | +author_data['date_time'] = pd.to_datetime(author_data['date_time']) |
| 84 | + |
| 85 | +# Plot the number of posts by the selected author per day using matplotlib |
| 86 | +plt.figure(figsize=(12, 6)) |
| 87 | +plt.plot(author_data['date_time'], author_data['content_count'], |
| 88 | + label=author_name, linestyle='-', color='blue') |
| 89 | +plt.title('Number of Posts per Author per Day') |
| 90 | +plt.xlabel('Date') |
| 91 | +plt.ylabel('Number of Posts') |
| 92 | +plt.grid(axis='y', linestyle='--') |
| 93 | +plt.tight_layout() |
| 94 | +plt.show() |
| 95 | + |
| 96 | +# Filter the DataFrame for the selected author's posts |
| 97 | +author_posts = post_data[post_data['author'] == author_name].copy() |
| 98 | + |
| 99 | +# Ensure that 'date_time' is in datetime format for plotting |
| 100 | +author_posts['date_time'] = pd.to_datetime( |
| 101 | + author_posts['date_time']) |
| 102 | + |
| 103 | +# Extract the content of the selected author's posts |
| 104 | +author_content = author_posts['content'] |
| 105 | + |
| 106 | +print(author_content) |
| 107 | + |
| 108 | +# Generate a word cloud from the selected author's posts content |
| 109 | +all_content = ' '.join(author_content.astype(str)) |
| 110 | +# Update the stop words to include common words that may not be useful in the word cloud |
| 111 | +updated_stop_words = STOPWORDS.update(["https", "co", "t"]) |
| 112 | +# Generate the word cloud using WordCloud from wordcloud library |
| 113 | +wordcloud = WordCloud(stopwords=updated_stop_words, width=800, |
| 114 | + height=400, background_color="white").generate(all_content) |
| 115 | + |
| 116 | +# Display the generated word cloud using matplotlib |
| 117 | +plt.figure(figsize=(10, 5)) |
| 118 | +plt.imshow(wordcloud) |
| 119 | +plt.axis("off") |
| 120 | +plt.show() |
| 121 | + |
| 122 | +# Convert 'date_time' to datetime format for accurate plotting |
| 123 | +author_posts['date_time'] = pd.to_datetime( |
| 124 | + author_posts['date_time']) |
| 125 | + |
| 126 | +print(author_posts) |
| 127 | + |
| 128 | +# Plot the daily number of likes and shares for the selected author using matplotlib |
| 129 | +plt.figure(figsize=(12, 6)) |
| 130 | +plt.plot(author_posts['date_time'], author_posts['number_of_likes'], |
| 131 | + label='Daily Likes', linestyle='-', color='blue') |
| 132 | +plt.plot(author_posts['date_time'], author_posts['number_of_shares'], |
| 133 | + label='Daily Shares', linestyle='-', color='orange') |
| 134 | +plt.title(f'Daily Likes and Shares for {author_name}') |
| 135 | +plt.xlabel('Date') |
| 136 | +plt.ylabel('Count of Likes/Shares') |
| 137 | +plt.legend() |
| 138 | +plt.grid(axis='y', linestyle='--') |
| 139 | +plt.tight_layout() |
| 140 | +plt.show() |
| 141 | + |
| 142 | + |
| 143 | +# Plot the daily number of likes and shares for the selected author using Plotly Express |
| 144 | +fig = px.line( |
| 145 | + author_posts, |
| 146 | + x='date_time', |
| 147 | + y=['number_of_likes', 'number_of_shares'], |
| 148 | + labels={'date_time': 'Date', 'value': 'Count'}, |
| 149 | + title=f'Daily Likes and Shares for {author_name}', |
| 150 | + markers=True, |
| 151 | + color_discrete_map={'number_of_likes': 'blue', |
| 152 | + 'number_of_shares': 'orange'} |
| 153 | +) |
| 154 | +fig.update_layout( |
| 155 | + xaxis_title='Date', |
| 156 | + yaxis_title='Count of Likes/Shares', |
| 157 | + legend_title='Metrics' |
| 158 | +) |
| 159 | +fig.show() |
| 160 | + |
| 161 | + |
| 162 | +# ending message |
| 163 | +print("Thank you for using the Social Media Analyzer!") |
| 164 | +print("-" * 75) |
| 165 | +print("We hope you found the analysis and visualizations helpful.") |
| 166 | +print("Feel free to explore the data further or modify the code for your own analysis.") |
| 167 | +print("-" * 75) |
| 168 | +print("Goodbye!") |
| 169 | +print("-" * 75) |
0 commit comments