Created
April 4, 2025 23:21
-
-
Save hakkm/0615d141bab8a2d6305d76e4f2ca5446 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tweepy | |
import openai | |
import matplotlib.pyplot as plt | |
import pandas as pd | |
import time | |
# ----------------------------- | |
# Configuration (Replace with your API keys) | |
# ----------------------------- | |
TWITTER_API_KEY = "YOUR_TWITTER_API_KEY" | |
TWITTER_API_SECRET = "YOUR_TWITTER_API_SECRET" | |
TWITTER_ACCESS_TOKEN = "YOUR_TWITTER_ACCESS_TOKEN" | |
TWITTER_ACCESS_TOKEN_SECRET = "YOUR_TWITTER_ACCESS_TOKEN_SECRET" | |
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" | |
# ----------------------------- | |
# Twitter API Setup | |
# ----------------------------- | |
auth = tweepy.OAuth1UserHandler( | |
TWITTER_API_KEY, TWITTER_API_SECRET, | |
TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET | |
) | |
twitter_api = tweepy.API(auth) | |
# ----------------------------- | |
# Data Collection Function | |
# ----------------------------- | |
def get_tweets(query, count=50): | |
""" | |
Fetches tweets based on a query. | |
""" | |
try: | |
tweets = twitter_api.search_tweets(q=query, count=count, lang="en", tweet_mode="extended") | |
tweet_texts = [tweet.full_text for tweet in tweets] | |
return tweet_texts | |
except Exception as e: | |
print("Error fetching tweets:", e) | |
return [] | |
# ----------------------------- | |
# Sentiment Analysis via OpenAI | |
# ----------------------------- | |
def analyze_sentiment(text): | |
""" | |
Uses OpenAI's API to analyze sentiment. | |
Returns sentiment as a string (e.g., Positive, Negative, Neutral). | |
""" | |
openai.api_key = OPENAI_API_KEY | |
try: | |
# Define a simple prompt for sentiment analysis | |
prompt = f"Analyze the sentiment of the following text and return only the sentiment (Positive, Negative, or Neutral):\n\n{text}" | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", # or gpt-4 if available | |
messages=[{"role": "user", "content": prompt}], | |
max_tokens=10, | |
n=1, | |
stop=None, | |
temperature=0.5 | |
) | |
sentiment = response.choices[0].message["content"].strip() | |
return sentiment | |
except Exception as e: | |
print("Error analyzing sentiment:", e) | |
return "Unknown" | |
# ----------------------------- | |
# Visualization Function | |
# ----------------------------- | |
def visualize_results(results): | |
""" | |
Visualizes the sentiment results in a bar chart. | |
""" | |
df = pd.DataFrame(results, columns=["Text", "Sentiment"]) | |
sentiment_counts = df["Sentiment"].value_counts() | |
plt.figure(figsize=(8, 6)) | |
sentiment_counts.plot(kind="bar", color=['green', 'red', 'blue']) | |
plt.xlabel("Sentiment") | |
plt.ylabel("Number of Tweets") | |
plt.title("Sentiment Analysis of Tweets") | |
plt.xticks(rotation=0) | |
plt.tight_layout() | |
plt.show() | |
# ----------------------------- | |
# Main Execution | |
# ----------------------------- | |
if __name__ == "__main__": | |
query = "local transportation issues" # Customize your search query | |
print("Fetching tweets for query:", query) | |
tweets = get_tweets(query, count=50) | |
if not tweets: | |
print("No tweets found or an error occurred.") | |
else: | |
results = [] | |
print("Analyzing sentiment of fetched tweets...") | |
for tweet in tweets: | |
sentiment = analyze_sentiment(tweet) | |
results.append((tweet, sentiment)) | |
time.sleep(1) # Pause to respect API rate limits | |
# Show a sample of results | |
for i, (text, sentiment) in enumerate(results[:3]): | |
print(f"Tweet {i+1}: {sentiment} -> {text[:80]}...") | |
# Visualize the sentiment distribution | |
visualize_results(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment