Skip to content
Snippets Groups Projects

Deleted twitter-scrapper.py

Compare and
1 file
+ 0
87
Compare changes
  • Side-by-side
  • Inline
import json
import csv
import tweepy
import re
import os
import pandas as pd
import datetime
import claves_twitter as ct
#Función que elimina emojis de las cadenas de texto
def remove_emoji(string):
patron_emoji = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
return patron_emoji.sub(r'', string)
def clean_tweet(text):
text=remove_emoji(text)
text=re.sub(r'http\S+', '', text) #Eliminación de urls
#text=re.sub(r'@[A-Za-z0-9]+','',text) #Eliminación de menciones, ¿necesario?
return text
def busqueda_por_hashtag(consumer_key, consumer_secret, access_token, access_token_secret, hash):
#Autenticación para acceder a la API de Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#Inicialización de la API de Twitter
api = tweepy.API(auth)
#Creación del dataframe donde se almacenarán las búsquedas
df=pd.DataFrame({
'Fecha':[],
'Mensaje':[]
})
ind=0
#Recorrido de tweets que coincidan con el hashtag
for tweet in tweepy.Cursor(api.search, q=hash+' -filter:retweets', \
lang="es", tweet_mode='extended').items(1000):
#Tratamiento fecha
fecha=tweet.created_at
#dia=fecha.split()[0]
#hora=fecha.split()[1] Si quisiéramos separarlo en día y hora
#Tratamiento de texto
texto=tweet.full_text.replace('\n',' ')
texto=clean_tweet(texto)
df.loc[ind]=[fecha]+[texto]
ind+=1
#Almacenamiento de los datos recogidos
hoy=datetime.date.today()
try:
os.mkdir('datos')
except:
pass
nombre_archivo='datos/twitter-'+str(hoy)+'.xlsx'
try:
with pd.ExcelWriter(nombre_archivo,mode='a') as writer:
df.to_excel(writer, sheet_name='hoja',index=None)
except:
df.to_excel(nombre_archivo,index = None, header=True,sheet_name='hoja')
def coloca_hashtags(lista):
final=lista[0]
lista.pop(0)
for i in lista:
final=final+' OR '+i
return final
#Hashtag a buscar (si no pones el hastahg busca palabras) y con OR o AND se puede meter en la variable q
lista= ['alegria','feliz','felicidad','alegre','diversión','divertido']
if __name__ == '__main__':
busqueda_por_hashtag(ct.consumer_key, ct.consumer_secret, ct.access_token, ct.access_token_secret, coloca_hashtags(lista))
Loading