Todas las Noticias en Películas, Avances de Películas y Reseñas.

API de Twitter con Python: todo lo que necesitas saber

Exploraremos varios datos de redes sociales a los que se accede desde Gorjeo API con Python en este blog. Para acceder a los datos, utilizaremos la API RESTful de Twitter y averiguaremos tanto sobre los usuarios de Twitter como sobre lo que tuitean. Tienes que hacer lo siguiente para empezar:

  • En primer lugar, si no tienes una cuenta de Twitter, crea una.
  • En segundo lugar, debe solicitar el Acceso de desarrollador utilizando su cuenta de Twitter. Después de hacerlo, cree una aplicación que generará las credenciales de la API. Esto es lo que usarás para acceder a Twitter desde Python.
  • Por último, debe importar el paquete tweepy.

Después de hacer las cosas mencionadas anteriormente, comencemos a consultar la API de Twitter y aprendamos sobre los tweets.

Lea también: Biblioteca de imágenes para Python: todo lo que necesita saber

Configuración de la aplicación de Twitter

Después de solicitar el Acceso de desarrollador, puede crear fácilmente una aplicación en Twitter a través de la cual puede acceder a los tweets. Asegúrese de que ya tiene una cuenta de Twitter.

Nota: Debe proporcionar un número de teléfono móvil que recibirá mensajes de texto en Twitter para verificar su uso de la API.

Accede a la API de Twitter en Python

Después de configurar la aplicación de Twitter, estará listo para acceder a los tweets en Python. Comencemos por importar las bibliotecas de Python necesarias.

import os
import tweepy as tw
import pandas as pd

Necesitará 4 elementos de la página de la aplicación de Twitter para poder acceder a la API de Twitter. Encontrará estas claves en la configuración de su aplicación de Twitter en la pestaña Claves y tokens de acceso.

  • clave de token de acceso
  • clave de consumidor
  • clave secreta del token de acceso
  • clave secreta del consumidor

Le recomendamos que no los comparta con nadie, ya que estos valores son específicos de su aplicación.

En primer lugar, defina sus claves:

consumer_key= 'yourkeyhere'
consumer_secret="yourkeyhere"
access_token= 'yourkeyhere'
access_token_secret="yourkeyhere"
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)

Enviar un tuit

Con la ayuda de su acceso API, puede enviar tweets. Pero asegúrese de que su tweet tenga 280 caracteres o menos.

# Post a tweet from Python
api.update_status("Look, I'm tweeting from #Python in my #earthanalytics class! @EarthLabCU")
# Your tweet has been posted!

Buscar tuits en Twitter

Ya está todo listo para buscar tweets recientes en Twitter ahora. En primer lugar, encuentre algunos tweets recientes que usen el hashtag #wildfires. Puede usar el método .Cursor para obtener un objeto que contenga tweets del hashtag #wildfires.

Recomendado:  Mira cuáles fueron las publicaciones más leídas de la semana (13/10 – 19/10)

Debe definir lo siguiente para crear esta consulta:

  • Término de búsqueda: según el ejemplo anterior #wildfires
  • Además, la fecha de inicio de la búsqueda.

Tenga en cuenta que la API de Twitter solo le permitirá acceder a los tweets de las últimas semanas, por lo que no podrá profundizar demasiado en el historial.

# Define the search term and the date_since date as variables
search_words = "#wildfires"
date_since = "2018-11-16"

Ahora debe usar .Cursor() para buscar tweets que contengan el término de búsqueda #wildfires en Twitter. Tiene la opción de restringir la cantidad de tweets especificando un número a través del método .items().

# Collect tweets
tweets = tw.Cursor(api.search,
              q=search_words,
              lang="en",
              since=date_since).items(5)
tweets
<tweepy.cursor.ItemIterator at 0x7fafc296e400>

.Cursor() tiene la capacidad de devolver un objeto a través del cual puede iterar o recorrer para acceder a los datos recopilados. Hay varios atributos disponibles para cada elemento en el iterador a través de los cuales puede acceder a la información sobre cada tweet. La información incluirá:

  • contenido del tuit,
  • nombre del remitente del tweet,
  • la fecha en que se envió el tweet, etc.

El código mencionado a continuación recorre las impresiones y los objetos del texto asociado con cada tweet.

# Collect tweets
tweets = tw.Cursor(api.search,
              q=search_words,
              lang="en",
              since=date_since).items(5)

# Iterate and print tweets
for tweet in tweets:
    print(tweet.text)
    
2/2 provide forest products to local mills, provide jobs to local communities, and improve the ecological health of… https://t.co/XemzXvyPyX
1/2 Obama's Forest Service Chief in 2015 -->"Treating these acres through commercial thinning, hazardous fuels remo… https://t.co/01obvjezQW
RT @EnviroEdgeNews: US-#Volunteers care for abandoned #pets found in #California #wildfires; #Dogs, #cats, [#horses], livestock get care an…
RT @FairWarningNews: The wildfires that ravaged CA have been contained, but the health impacts from the resulting air pollution will be sev…
RT @chiarabtownley: If you know anybody who has been affected by the wildfires, please refer them to @awarenow_io It is one of the companie…

En el enfoque anterior, hemos utilizado un bucle for estándar. Pero es un gran lugar para usar la comprensión de listas de Python. Con la ayuda de la comprensión de una lista, puede recopilar de manera eficiente elementos de objetos contenidos en un iterador como una lista.

# Collect tweets
tweets = tw.Cursor(api.search,
                       q=search_words,
                       lang="en",
                       since=date_since).items(5)

# Collect a list of tweets
[tweet.text for tweet in tweets]
['Expert insight on how #wildfires impact our environment: https://t.co/sHg6PcC3R3',
 'Lomakatsi crews join the firefight: \n\n#wildfires #smoke #firefighter\n\nhttps://t.co/DcI2uvmKQv',
 'RT @rpallanuk: Current @PHE_uk #climate extremes bulletin: #Arctic #wildfires & Greenland melt, #drought in Australia/NSW; #flooding+#droug…',
 "RT @witzshared: And yet the lies continue. Can't trust a corporation this deaf dumb and blind -- PG&E tells court deferred #Maintenance did…",
 'The #wildfires have consumed an area twice the size of Connecticut, and their smoke is reaching Seattle. Russia isn… https://t.co/SgoF6tds1s']

Para eliminar o mantener Retweets

Cuando alguien más comparte su tweet, se llama Retweet. Es básicamente como compartir en Facebook u otras aplicaciones de redes sociales. Muchas veces quieres mantener estos retweets o eliminarlos por duplicidad de contenidos. En el comando mencionado a continuación, ignorará todos los retweets agregando -filter:retweets a su consulta. La documentación de la API de Twitter puede personalizar sus consultas de otras formas.

new_search = search_words + " -filter:retweets"
new_search
'#wildfires -filter:retweets'
tweets = tw.Cursor(api.search, q=new_search, lang="en", since=date_since).items(5)

[tweet.text for tweet in tweets]
['@HARRISFAULKNER over 10% of a entire state (#Oregon) has been displaced due to #wildfires which is unprecedented, a… https://t.co/SJPyDw2vGZ',
 'I left a small window open last night and the smoke from the outside #wildfires made our smoke alarm go off at 4 am… https://t.co/qj79wtXZ7o',
 '5 of the 10 biggest #wildfires in California history are burning right now.\n\nFossil fuels brought the… https://t.co/BqRZvnj7Ir',
 '#Wildfires are part of a vicious cycle: their #emissions fuel global heating, leading to ever-worse fires, which re… https://t.co/OA4UZoFbn8',
 'This could be helpful if you need to evacuate!\n#wildfires #OregonIsBurning https://t.co/7F

Who is tweeting about wildfires?

There is so much information you can access that is associated with every tweet. We have mentioned an illustration below of accessing the users who are sending the tweets related to #wildfires and their locations. Please note that since user locations are entered manually by the user into Twitter, you may see a many variation in the format of this value.

  • tweet.user.screen_name gives information of the user’s twitter handle associated with each tweet.
  • tweet.user.location gives the location provided by the user.
Recomendado:  La defensa antimisiles L-SAM de Corea del Sur ha realizado pruebas, dicen las fuentes, ¿protección contra Corea del Norte?

You can type tweet. to experiment with other items available in every tweet. Then, use the tab button to see all of the available attributes stored.

tweets = tw.Cursor(api.search, 
                           q=new_search,
                           lang="en",
                           since=date_since).items(5)

users_locs = [[tweet.user.screen_name, tweet.user.location]  para tweet en tweets]users_locs
[['J___D___B', 'United States'],
 ['KelliAgodon', 'S E A T T L E  ☮ ?️\u200d?'],
 ['jpmckinnie', 'Los Angeles, CA'],
 ['jxnova', 'Harlem, USA'],
 ['momtifa', 'Portland, Oregon, USA']]

Cree un marco de datos de Pandas a partir de una lista de datos de Tweet

Hay una lista de elementos con los que desea trabajar y puede crear un marco de datos de pandas que contenga los datos.

tweet_text = pd.DataFrame(data=users_locs, 
                    columns=['user', "location"])
tweet_text
UsuarioUbicación
J___D___BEstados Unidos
mamátifaPortland, Oregón, EE. UU.
KelliAgodonSEATTLE ☮ ?️‍?
jxnovaHarlem, Estados Unidos
jpmckinnieLos Ángeles, California

Personalización de consultas de Twitter

Puede personalizar sus consultas de búsqueda de Twitter como ya mencionamos anteriormente con la ayuda de la documentación de la API de Twitter. Por ejemplo, cuando busca clima+cambio, Twitter proporcionará todos los tuits que contengan ambas palabras (en una fila) en cada tuit. En el código mencionado a continuación, crearemos una lista que se puede consultar utilizando la indexación de Python para devolver los primeros cinco tweets.

new_search = "climate+change -filter:retweets"

tweets = tw.Cursor(api.search,
                   q=new_search,
                   lang="en",
                   since="2018-04-23").items(1000)

all_tweets = [tweet.text for tweet in tweets]
all_tweets[:5]
['They care so much for these bears, but climate change is altering their relationship with them. It’s getting so dan… https://t.co/D4wLNhhsdt',
 'Prediction any celebrity/person in government that preaches about climate change probably is blackmailed… https://t.co/TM64QukGhy',
 '@RichardBurgon Brain washed and trying to do the same to others. Capitalism is ALL that "Climate Change" is about. https://t.co/GbNE87luVx',
 "We're in a climate crisis, but Canada's handing out billions to fossil fuel companies. Click to change this:… https://t.co/oQZXUfOWe8",
 'Hundreds Of Starved Reindeer Found Dead In Norway, Climate Change Blamed - Forbes #nordic #norway https://t.co/9XLS8yi72l']

Conclusión

En este blog, discutimos la API de Twitter con python y ahora lo tenemos claro. Gracias por leer el blog.

Recomendado:  Los parlantes para exteriores Sonance con tecnología Sonos tienen actualmente un descuento de $ 1,000 en Best Buy