Capítulo 17: Estudio de Caso 2: Análisis de Sentimientos en Redes Sociales
17.4 Ejercicios Prácticos
¡Fantástico! Acabas de navegar por un caso de estudio intrincado pero fascinante sobre el análisis de sentimientos en redes sociales. Ahora es el momento de ensuciarse las manos con algunos ejercicios prácticos que solidificarán tu comprensión. ¡Toma tu teclado y empecemos!
Ejercicio 1: Recolección de Datos
Recolecta 50 tweets que contengan el hashtag #Python
. Puedes hacerlo manualmente o mediante una API.
Solución:
# Note: You'll need Twitter API credentials for this
import tweepy
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.search(q='#Python', count=50)
for tweet in tweets:
print(tweet.text)
Ejercicio 2: Preprocesamiento de Texto
Elimina las palabras vacías y los caracteres especiales de los tweets recolectados en el Ejercicio 1.
Solución:
from nltk.corpus import stopwords
import re
stop_words = set(stopwords.words('english'))
def clean_text(text):
text = re.sub('[^a-zA-Z]', ' ', text)
text = text.lower().split()
text = [word for word in text if not word in stop_words]
return ' '.join(text)
cleaned_tweets = [clean_text(tweet.text) for tweet in tweets]
Ejercicio 3: Análisis de Sentimientos con Naive Bayes
Utiliza el modelo Naive Bayes que construiste anteriormente en el capítulo para clasificar los sentimientos de los tweets limpios.
Solución:
# Use the previously defined `extract_features` and `classifier`
test_data = [extract_features(tweet) for tweet in cleaned_tweets]
predictions = [classifier.classify(features) for features in test_data]
# Display the results
for i, (tweet, sentiment) in enumerate(zip(cleaned_tweets, predictions)):
print(f"Tweet {i+1}: {tweet} -> Sentiment: {sentiment}")
Siéntete libre de volver a estos ejercicios siempre que necesites un repaso o práctica adicional. Abordan los pasos críticos en el establecimiento y realización del análisis de sentimientos. ¡Disfruta programando!
17.4 Ejercicios Prácticos
¡Fantástico! Acabas de navegar por un caso de estudio intrincado pero fascinante sobre el análisis de sentimientos en redes sociales. Ahora es el momento de ensuciarse las manos con algunos ejercicios prácticos que solidificarán tu comprensión. ¡Toma tu teclado y empecemos!
Ejercicio 1: Recolección de Datos
Recolecta 50 tweets que contengan el hashtag #Python
. Puedes hacerlo manualmente o mediante una API.
Solución:
# Note: You'll need Twitter API credentials for this
import tweepy
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.search(q='#Python', count=50)
for tweet in tweets:
print(tweet.text)
Ejercicio 2: Preprocesamiento de Texto
Elimina las palabras vacías y los caracteres especiales de los tweets recolectados en el Ejercicio 1.
Solución:
from nltk.corpus import stopwords
import re
stop_words = set(stopwords.words('english'))
def clean_text(text):
text = re.sub('[^a-zA-Z]', ' ', text)
text = text.lower().split()
text = [word for word in text if not word in stop_words]
return ' '.join(text)
cleaned_tweets = [clean_text(tweet.text) for tweet in tweets]
Ejercicio 3: Análisis de Sentimientos con Naive Bayes
Utiliza el modelo Naive Bayes que construiste anteriormente en el capítulo para clasificar los sentimientos de los tweets limpios.
Solución:
# Use the previously defined `extract_features` and `classifier`
test_data = [extract_features(tweet) for tweet in cleaned_tweets]
predictions = [classifier.classify(features) for features in test_data]
# Display the results
for i, (tweet, sentiment) in enumerate(zip(cleaned_tweets, predictions)):
print(f"Tweet {i+1}: {tweet} -> Sentiment: {sentiment}")
Siéntete libre de volver a estos ejercicios siempre que necesites un repaso o práctica adicional. Abordan los pasos críticos en el establecimiento y realización del análisis de sentimientos. ¡Disfruta programando!
17.4 Ejercicios Prácticos
¡Fantástico! Acabas de navegar por un caso de estudio intrincado pero fascinante sobre el análisis de sentimientos en redes sociales. Ahora es el momento de ensuciarse las manos con algunos ejercicios prácticos que solidificarán tu comprensión. ¡Toma tu teclado y empecemos!
Ejercicio 1: Recolección de Datos
Recolecta 50 tweets que contengan el hashtag #Python
. Puedes hacerlo manualmente o mediante una API.
Solución:
# Note: You'll need Twitter API credentials for this
import tweepy
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.search(q='#Python', count=50)
for tweet in tweets:
print(tweet.text)
Ejercicio 2: Preprocesamiento de Texto
Elimina las palabras vacías y los caracteres especiales de los tweets recolectados en el Ejercicio 1.
Solución:
from nltk.corpus import stopwords
import re
stop_words = set(stopwords.words('english'))
def clean_text(text):
text = re.sub('[^a-zA-Z]', ' ', text)
text = text.lower().split()
text = [word for word in text if not word in stop_words]
return ' '.join(text)
cleaned_tweets = [clean_text(tweet.text) for tweet in tweets]
Ejercicio 3: Análisis de Sentimientos con Naive Bayes
Utiliza el modelo Naive Bayes que construiste anteriormente en el capítulo para clasificar los sentimientos de los tweets limpios.
Solución:
# Use the previously defined `extract_features` and `classifier`
test_data = [extract_features(tweet) for tweet in cleaned_tweets]
predictions = [classifier.classify(features) for features in test_data]
# Display the results
for i, (tweet, sentiment) in enumerate(zip(cleaned_tweets, predictions)):
print(f"Tweet {i+1}: {tweet} -> Sentiment: {sentiment}")
Siéntete libre de volver a estos ejercicios siempre que necesites un repaso o práctica adicional. Abordan los pasos críticos en el establecimiento y realización del análisis de sentimientos. ¡Disfruta programando!
17.4 Ejercicios Prácticos
¡Fantástico! Acabas de navegar por un caso de estudio intrincado pero fascinante sobre el análisis de sentimientos en redes sociales. Ahora es el momento de ensuciarse las manos con algunos ejercicios prácticos que solidificarán tu comprensión. ¡Toma tu teclado y empecemos!
Ejercicio 1: Recolección de Datos
Recolecta 50 tweets que contengan el hashtag #Python
. Puedes hacerlo manualmente o mediante una API.
Solución:
# Note: You'll need Twitter API credentials for this
import tweepy
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.search(q='#Python', count=50)
for tweet in tweets:
print(tweet.text)
Ejercicio 2: Preprocesamiento de Texto
Elimina las palabras vacías y los caracteres especiales de los tweets recolectados en el Ejercicio 1.
Solución:
from nltk.corpus import stopwords
import re
stop_words = set(stopwords.words('english'))
def clean_text(text):
text = re.sub('[^a-zA-Z]', ' ', text)
text = text.lower().split()
text = [word for word in text if not word in stop_words]
return ' '.join(text)
cleaned_tweets = [clean_text(tweet.text) for tweet in tweets]
Ejercicio 3: Análisis de Sentimientos con Naive Bayes
Utiliza el modelo Naive Bayes que construiste anteriormente en el capítulo para clasificar los sentimientos de los tweets limpios.
Solución:
# Use the previously defined `extract_features` and `classifier`
test_data = [extract_features(tweet) for tweet in cleaned_tweets]
predictions = [classifier.classify(features) for features in test_data]
# Display the results
for i, (tweet, sentiment) in enumerate(zip(cleaned_tweets, predictions)):
print(f"Tweet {i+1}: {tweet} -> Sentiment: {sentiment}")
Siéntete libre de volver a estos ejercicios siempre que necesites un repaso o práctica adicional. Abordan los pasos críticos en el establecimiento y realización del análisis de sentimientos. ¡Disfruta programando!