







Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!








library (readr) #Facilita la lectura de archivos .csv library (stopwords) #Lista de palabras comunes para eliminación library (wordcloud2) #Creacion de las nubes de palabras library (ggplot2) #Creacion de las gráficas library (readxl) #Facilita la lectura de archivos .xlsx library (tidytext) #Esctructuracion y análisis de textos library (dplyr) #Manipulacion del dataframe library (lubridate) #Manejo de fechas y horas library (openxlsx) #Manipulacion y escritura de archivos .xlsx library (tidyr) #Transformacion y reorganización de datos library (kableExtra) #Presentacion de tablas en R Mark Down library (svDialogs) #Interfaz de diálogos para Windows library (tweetbotornot) #Predice si una cuenta es un Bot o no library (stringr) #Manipulacion de cadenas de texto library (rtweet) #Analisis de datos de Twitter API library (webshot) #Captura de gráficos de R como imágenes library (htmlwidgets) #Manipulacion de HTML con R
setwd ("C:/Documentacion WebScraping")
token_acceso <- rtweet ::create_token (app = "", consumer_key = "", consumer_secret = "", access_token = "", access_secret = "")
busqueda <- " " Marcelo Ebrard " OR " Canciller Ebrard " OR m_ebrard OR " Ebrard " OR " carnal Marcelo " " fecha_inicio <- svDialogs ::dlgInput (message = "Fecha de inicio:") $ res numero_tweets <- svDialogs ::dlgInput (message = "Número de tweets solicitados:") $ res %>% as.numeric ()
fecha_carpeta <- svDialogs ::dlgInput (message = "Nombre de la carpeta:") $ res nombre_carpeta <- fecha_carpeta dir.create (fecha_carpeta)
tweets <- rtweet ::search_tweets (q = busqueda, n = numero_tweets, lang = "es", include_rts = FALSE, type = "recent", retryonratelimit = TRUE) %>% dplyr ::mutate (created_at = lubridate ::with_tz (created_at, tzone = "America/Mexico_City")) %>% dplyr ::mutate (account_created_at = lubridate ::with_tz (account_created_at, tzone = "America/Mexico_City")) %>% dplyr ::filter (screen_name != "m_ebrard") %>% dplyr ::filter (created_at >= fecha_inicio) %>% dplyr ::arrange ( desc (created_at))
tweets_nodos <- tweets %>% dplyr ::select (screen_name, reply_to_screen_name) tweets_nodos <- na.omit (tweets_nodos) rtweet ::write_as_csv (tweets_nodos, "tweets_nodos.csv") #CSV para redes de nodos
bot <- tweetbotornot ::botornot (tweets, fast = FALSE) tweets <- dplyr ::full_join (tweets, bot, by = "screen_name") bot <- NULL
tweets <- tweets %>% dplyr ::select (status_id, usuario = screen_name, nombre = name, seguidores = followers_count,
alcance <- tweets %>% dplyr ::group_by (usuario, nombre, seguidores) %>% dplyr ::summarise (publicaciones = dplyr ::n (), alcance = sum (seguidores), .groups = "keep") %>% dplyr ::arrange ( desc (alcance)) openxlsx ::write.xlsx (alcance, "02_alcance_general.xlsx") alcance %>% head ( 20 ) %>% kable () %>% kable_styling (full_width = TRUE, font_size = 20 , row_label_position = "c") %>% row_spec ( 0 , color = "#F5F8FA", background = "#1DA1F2") %>% column_spec ( 1 , bold = TRUE, border_right = TRUE, color = "#F5F8FA", background = "#657786") %>% save_kable ("02_alcance_general.png")
lideres <- readxl ::read_xlsx ("C:/Desarrollo Python/WebScraping Twitter/clasificacion_usuarios.xlsx", sheet = "lideres", col_names = TRUE,) %>%
dplyr ::pull () tweets_lideres <- tweets1 %>% dplyr ::filter (usuario %in% lideres) %>% dplyr ::arrange ( desc (fecha)) openxlsx ::write.xlsx (tweets_lideres, "03_tweets_lideres.xlsx")
alcance_lideres <- tweets_lideres %>% dplyr ::group_by (usuario, nombre, seguidores) %>% dplyr ::summarise (publicaciones = dplyr ::n (), alcance = sum (seguidores), .groups = "keep") %>% dplyr ::arrange ( desc (alcance)) openxlsx ::write.xlsx (alcance_lideres, "03_alcance_lideres.xlsx") alcance_lideres %>% head ( 20 ) %>% kable () %>% kable_styling (full_width = TRUE, font_size = 20 ) %>% row_spec ( 0 , color = "#F5F8FA", background = "#1DA1F2") %>% column_spec ( 1 , bold = TRUE, border_right = TRUE, color = "#F5F8FA", background = "#657786") %>% save_kable ("03_alcance_lideres.png")
tweets_lideres %>% dplyr ::count (nombre, sort = TRUE) %>% dplyr ::mutate (nombre = reorder (nombre, n)) %>% head ( 10 ) %>% ggplot ( aes (x = nombre, y = n, fill = n)) + geom_col (show.legend = FALSE) + coord_flip () +
geom_text ( aes (label = n), hjust = - 0.2, size = 4 ) + labs (title = "Medios de comunicación", subtitle = "Usuarios con más tweets emitidos", x = NULL, y = "cantidad de tweets", caption = "Fuente: Twitter, Inc.") ggplot2 ::ggsave ("06_medios_locales.png", width = 25 , height = 12.5, units = "cm", device = "png", dpi = "retina")
alcance_medios <- tweets_medios %>% dplyr ::group_by (usuario, nombre, seguidores) %>% dplyr ::summarise (publicaciones = dplyr ::n (), alcance = sum (seguidores), .groups = "keep") %>% dplyr ::arrange ( desc (alcance)) openxlsx ::write.xlsx (alcance_medios, "06_alcance_medios_locales.xlsx") alcance_medios %>% head ( 20 ) %>% kable () %>% kable_styling (full_width = TRUE, font_size = 20 ) %>% row_spec ( 0 , color = "#F5F8FA", background = "#1DA1F2") %>% column_spec ( 1 , bold = TRUE, border_right = TRUE, color = "#F5F8FA", background = "#657786") %>% save_kable ("06_alcance_medios_locales.png")
tweets_token <- tweets %>% tidytext ::unnest_tokens (output = "palabra", input = "tweet", token = "words") %>% dplyr ::anti_join (palabras_vacias, by = c ("palabra" = ".")) %>% dplyr ::anti_join (palabras_custom, by = c ("palabra" = "."))
tweets_palabras <- tweets_token %>% dplyr ::count (palabra, sort = TRUE) %>% dplyr ::mutate (palabra = reorder (palabra, n)) %>% head ( 50 ) wordcloud2 ::wordcloud2 (tweets_palabras, size = 1 , color = "#B38E5D") nube <- wordcloud2 (data = tweets_palabras, size = 1 , color = "#B38E5D") htmlwidgets ::saveWidget (nube, "C:/Desarrollo Python/WebScraping Twitter/Reporte Diario/MarceloEbrard/nube_palabras.html",
row_spec ( 0 , color = "#F5F8FA", background = "#1DA1F2") %>% column_spec ( 1 , bold = TRUE, border_right = TRUE, color = "#F5F8FA", background = "#657786") %>% save_kable ("05_alcance_embajadas.png")
tweets_embajadas %>% dplyr ::count (nombre, sort = TRUE) %>% dplyr ::mutate (nombre = reorder (nombre, n)) %>% head ( 10 ) %>% ggplot ( aes (x = nombre, y = n, fill = n)) + geom_col (show.legend = FALSE) + coord_flip () + theme_classic () + scale_fill_gradient (low = "#B38E5D", high = "#4E232E") + geom_text ( aes (label = n), hjust = - 0.2, size = 4 ) + labs (title = "Embajadas", subtitle = "Embajadas con más tweets emitidos", x = NULL, y = "cantidad de tweets", caption = "Fuente: Twitter, Inc.") ggplot2 ::ggsave ("05_embajadas.png", width = 25 , height = 12.5, units = "cm", device = "png", dpi = "retina")
medios_internacionales <- readxl ::read_xlsx ("C:/Desarrollo Python/WebScraping Twitter/clasificacion_usuarios.xlsx", sheet = "internacionales", col_names = TRUE,) %>% dplyr ::pull () tweets_internacionales <- tweets1 %>% dplyr ::filter (usuario %in% medios_internacionales) %>% dplyr ::arrange ( desc (fecha)) openxlsx ::write.xlsx (tweets_internacionales, "04_tweets_medios_internacionales.xlsx")
alcance_internacionales <- tweets_internacionales %>% dplyr ::group_by (usuario, nombre, seguidores) %>% dplyr ::summarise (publicaciones = dplyr ::n (), alcance = sum (seguidores), .groups = "keep") %>% dplyr ::arrange ( desc (alcance)) openxlsx ::write.xlsx (alcance_internacionales, "04_alcance_medios_internacionales.xlsx") alcance_internacionales %>% head ( 20 ) %>% kable () %>% kable_styling (full_width = TRUE, font_size = 20 ) %>% row_spec ( 0 , color = "#F5F8FA", background = "#1DA1F2") %>% column_spec ( 1 , bold = TRUE, border_right = TRUE, color = "#F5F8FA", background = "#657786") %>% save_kable ("04_alcance_medios_internacionales.png")
tweets_internacionales %>% dplyr ::count (nombre, sort = TRUE) %>% dplyr ::mutate (nombre = reorder (nombre, n)) %>% head ( 10 ) %>% ggplot ( aes (x = nombre, y = n, fill = n)) + geom_col (show.legend = FALSE) + coord_flip () + theme_classic () + scale_fill_gradient (low = "#B38E5D", high = "#4E232E") + geom_text ( aes (label = n), hjust = - 0.2, size = 4 ) + labs (title = "Medios internacionales", subtitle = "Medios internacionales con más tweets emitidos", x = NULL,