You are on page 1of 2

# myapp/views.

py
from django.shortcuts import render
from tweepy import OAuth1UserHandler, API
from textblob import TextBlob
import pickle

# Load the trained classifier from a file


with open("classifier.pkl", "rb") as f:
classifier = pickle.load(f)

# Connect to the Twitter API using tweepy


consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"

auth = OAuth1UserHandler(consumer_key, consumer_secret, access_token,


access_token_secret)
api = API(auth)

def home(request):
# Render the home template
return render(request, "home.html")

def search(request):
# Get the search term from the user's input
search_term = request.GET["search_term"]

# Search for tweets containing the search term


tweets = api.search_tweets(q=search_term, lang="en")

# Extract features from the tweets using TextBlob


X = []
for tweet in tweets:
text = tweet.text
sentiment = TextBlob(text).sentiment.polarity
subjectivity = TextBlob(text).sentiment.subjectivity
X.append([sentiment, subjectivity])

# Use the classifier to predict the labels of the tweets


predictions = classifier.predict(X)

# Render the results template with the search term and predictions
return render(request, "results.html", {"search_term": search_term,
"predictions": predictions})

<!-- myapp/templates/home.html -->


<form method="get" action="/search/">
<input type="text" name="search_term" placeholder="Enter a search term">
<button type="submit">Search</button>
</form>
<!-- myapp/templates/results.html -->
<p>Results for: {{ search_term }}</p>
<ul>
{% for prediction in predictions %}
<li>{{ prediction }}</li>
{% endfor %}
</ul>

You might also like