##### Se instalan las librerias que se utilizaran durante todo el proceso.
library(rvest)
## Warning: package 'rvest' was built under R version 4.2.3
library(magrittr)
library(httr)
## Warning: package 'httr' was built under R version 4.2.3
library(tm)
## Warning: package 'tm' was built under R version 4.2.3
## Loading required package: NLP
##
## Attaching package: 'NLP'
## The following object is masked from 'package:httr':
##
## content
# Ruta de la carpeta donde están los archivos seleccionados
carpeta_destino <- "C:/Users/santi/OneDrive/Documentos/CIENCIAS DE DATOS 2/TXT RETO/TXT 2022"
# Listar todos los archivos en la carpeta de destino
archivos_en_carpeta <- list.files(path = carpeta_destino)
##### Limpieza de archivos
# Crear una función para limpiar el texto
limpiar_texto <- function(archivo) {
# Leer el contenido del archivo
contenido <- readLines(file.path(carpeta_destino, archivo), warn = FALSE)
contenido <- paste(contenido, collapse = " ")
# Eliminar URLs
contenido <- gsub("http\\S+|www\\.\\S+", "", contenido)
# Eliminar etiquetas HTML
contenido <- gsub("<.*?>", "", contenido)
# Eliminar puntuación
contenido <- gsub("[[:punct:]]", "", contenido)
# Eliminar números
contenido <- gsub("\\d+", "", contenido)
# Eliminar espacios extra
contenido <- gsub("\\s+", " ", contenido)
# Convertir a minúsculas
contenido <- tolower(contenido)
return(contenido)
}
# Aplicar la función de limpieza a cada archivo en la carpeta
textos_limpios <- lapply(archivos_en_carpeta, limpiar_texto)
# Importar las librerías necesarias
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.3
## Warning: package 'tibble' was built under R version 4.2.3
## Warning: package 'tidyr' was built under R version 4.2.3
## Warning: package 'readr' was built under R version 4.2.3
## Warning: package 'dplyr' was built under R version 4.2.3
## Warning: package 'stringr' was built under R version 4.2.3
## Warning: package 'lubridate' was built under R version 4.2.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.3 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.4 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ ggplot2::annotate() masks NLP::annotate()
## ✖ NLP::content() masks httr::content()
## ✖ tidyr::extract() masks magrittr::extract()
## ✖ dplyr::filter() masks stats::filter()
## ✖ readr::guess_encoding() masks rvest::guess_encoding()
## ✖ dplyr::lag() masks stats::lag()
## ✖ purrr::set_names() masks magrittr::set_names()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidytext)
## Warning: package 'tidytext' was built under R version 4.2.3
library(dplyr)
library(sentimentr)
## Warning: package 'sentimentr' was built under R version 4.2.3
library(topicmodels)
## Warning: package 'topicmodels' was built under R version 4.2.3
library(tm)
library(ggplot2)
#MEJORA: realizar un loop o algoritmo para analizar todos los textos
# HINT: agrupen sus textos en txt NO LOS SOBREESCRIBAN UNO DEL OTRO
# Leer el archivo txt
transcription <- read_file("Día Mundial contra la Obesidad _ 4 de marzo _ Instituto de Salud para el Bienestar _ Gobierno _ gob.mx.txt")
# Preprocesar el texto
transcription <- gsub("\n", " ", transcription)
transcription <- tolower(transcription)
transcription <- removePunctuation(transcription)
transcription <- removeWords(transcription, stopwords("spanish"))
# Analizar el sentimiento
sentiment <- sentiment_by(transcription)
# Convertir el texto en un Corpus
corpus <- Corpus(VectorSource(transcription))
# Convertir el texto en un DocumentTermMatrix
dtm <- DocumentTermMatrix(corpus)
# Generar un modelo de topic models
lda <- LDA(dtm, k = 5)
# Obtener los términos más importantes de cada tópico
terms <- tidy(lda, matrix = "beta") %>%
group_by(topic) %>%
top_n(5, wt = beta)
# Generar el gráfico
ggplot(terms, aes(x = term, y = beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
coord_flip() +
facet_wrap(~topic, ncol = 3)
terms <- tidy(lda, matrix = "beta")
terms <- terms %>%
select(term, beta)
#beta= importancia -> que tan pegados estpan a otros elementos del tópico.
# Importar las librerías necesarias
library(tidyverse)
library(tidytext)
library(dplyr)
library(topicmodels)
library(tm)
library(ggplot2)
# Crear una función para analizar un archivo de texto
analyze_text <- function(file_path) {
# Leer el archivo txt
transcription <- read_file(file_path)
# Preprocesar el texto
transcription <- gsub("\n", " ", transcription)
transcription <- tolower(transcription)
transcription <- removePunctuation(transcription)
transcription <- removeWords(transcription, stopwords("spanish"))
# Verificar que el documento no esté vacío
if (nchar(transcription) > 0) {
# Convertir el texto en un Corpus
corpus <- Corpus(VectorSource(transcription))
# Convertir el texto en un DocumentTermMatrix
dtm <- DocumentTermMatrix(corpus)
# Verificar que el DTM contenga al menos un término
if (length(dtm$dimnames$Terms) > 0) {
# Generar un modelo de topic models
lda <- LDA(dtm, k = 5)
# Obtener los términos más importantes de cada tópico
terms <- tidy(lda, matrix = "beta") %>%
group_by(term) %>%
summarize(frequency = sum(beta))
return(terms)
}
}
return(NULL) # Si el documento no contiene datos válidos
}
# Ruta de la carpeta que contiene los archivos de texto
carpeta_textos <- "C:/Users/santi/OneDrive/Documentos/CIENCIAS DE DATOS 2/TXT RETO/TXT 2022"
# Listar los archivos de texto en la carpeta
archivos_texto <- list.files(path = carpeta_textos, pattern = "\\.txt", full.names = TRUE)
# Inicializar una lista para almacenar los resultados
resultados <- list()
# Iterar a través de los archivos y analizar cada uno
for (archivo in archivos_texto) {
resultado <- analyze_text(archivo)
if (!is.null(resultado)) {
resultados[[archivo]] <- resultado
}
}
# Combinar y filtrar los resultados de términos más frecuentes
resultados_combinados <- bind_rows(resultados)
top_terms <- resultados_combinados %>%
group_by(term)
# Obtener los términos más importantes de cada tópico
terms <- tidy(lda, matrix = "beta")
# Ordenar los términos por beta de mayor a menor y seleccionar los 15 primeros
top_terms <- terms %>%
arrange(desc(beta)) %>%
top_n(10)
## Selecting by beta
# Agregar la información del tema a resultados_combinados
resultados_combinados <- resultados_combinados %>%
right_join(top_terms, by = c("term" = "term"))
## Warning in right_join(., top_terms, by = c(term = "term")): Detected an unexpected many-to-many relationship between `x` and `y`.
## ℹ Row 5198 of `x` matches multiple rows in `y`.
## ℹ Row 9 of `y` matches multiple rows in `x`.
## ℹ If a many-to-many relationship is expected, set `relationship =
## "many-to-many"` to silence this warning.
# Visualizar los términos más frecuentes con facet_wrap
ggplot(resultados_combinados, aes(x = term, y = beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
coord_flip() +
facet_wrap(~topic, ncol = 3)
##### Creamos un corpus limpio
##### Unimos en un mismo vector la función anterior
# Crear un vector llamado "Texto Limpio"
textos_limpios <- lapply(archivos_en_carpeta, limpiar_texto)
# Combinar los textos limpios en un solo vector
TextoLimpio <- unlist(textos_limpios)
##### Análisis Exploratorio en el que se crea la Matriz de Términos de Documento e identifica y lista los términos más frecuentes en el conjunto de datos.
library(tm)
# Crear un Corpus con los textos
corpus <- Corpus(VectorSource(TextoLimpio))
#Documetn Term Matrix
dtm <- DocumentTermMatrix(corpus)
#Ver la Matriz
inspect(dtm)
## <<DocumentTermMatrix (documents: 7, terms: 7381)>>
## Non-/sparse entries: 8725/42942
## Sparsity : 83%
## Maximal term length: 78
## Weighting : term frequency (tf)
## Sample :
## Terms
## Docs con del género las los mujeres nacional para por que
## 1 1215 1426 656 2272 1433 1365 522 1755 457 1082
## 2 8 15 0 8 7 0 1 12 14 13
## 3 2 8 0 14 11 5 0 2 6 5
## 4 8 18 0 17 14 1 0 6 9 19
## 5 13 14 1 16 7 1 2 12 6 9
## 6 2 2 0 2 6 0 0 2 0 4
## 7 2 2 0 2 6 0 0 2 0 4
##### Se eliminan stopwords y palabras específicas que no funcionan al análisis
# Lista de palabras específicas no deseadas
palabras_no_deseadas <- c("años","sé","ser","aún","gracias","dianina","cómo","cada","bueno","italia","sólo","saludos","tal","ahí","hola","creo","vídeo","pues","ver","vez","dos","aquí","caso","dios","etc","hace","misma","veo","todas","día","año","voy","dice","así","ello","sino","casi","video","entiendo","iba","dia","toda","igual","decir","aun","canal","tan","asillevo","hago","super","siempre","ahora","hoy","cosa","entonces","videos","alguien","pasa","veces","ole","mas","gente","cosas","muchas","verdad","mismo")
# Eliminar stopwords de nuestro corpus
corpus_limpio <- tm_map(corpus, removeWords, stopwords("es"))
## Warning in tm_map.SimpleCorpus(corpus, removeWords, stopwords("es")):
## transformation drops documents
# Eliminar palabras específicas no deseadas
corpus_limpio <- tm_map(corpus_limpio, removeWords, palabras_no_deseadas)
## Warning in tm_map.SimpleCorpus(corpus_limpio, removeWords,
## palabras_no_deseadas): transformation drops documents
# Crear el nuevo DocumentTermMatrix
dtm_limpio <- DocumentTermMatrix(corpus_limpio)
# Sumar las columnas para obtener el conteo total de cada término
conteo_total_limpio <- colSums(as.matrix(dtm_limpio))
# Ordenar y mostrar los términos más comunes
terminos_comunes_limpio <- sort(conteo_total_limpio, decreasing = TRUE)
library(ggplot2)
# Definir una lista de colores personalizada
mis_colores <- c("#8A2BE2", "#FF5F8D", "#FFAE66", "#0038B3", "#66CCFF", "#B38EB3", "#EEDD44", "#805380", "#FF6944", "#008E00", "#4E9B71", "#45A6E6", "#A89400", "#D27B45", "#A88945")
# Obtener los 15 términos más comunes
top_15_terminos <- head(terminos_comunes_limpio, 15)
# Crear un data frame con los términos y sus conteos
data <- data.frame(Término = names(top_15_terminos), Conteo = top_15_terminos)
# Crear la gráfica de barras utilizando la lista de colores personalizada
ggplot(data, aes(x = reorder(Término, -Conteo), y = Conteo)) +
geom_bar(stat = "identity", fill = mis_colores) +
labs(title = "Los 15 términos más comunes en el 2021", x = "Término", y = "Conteo") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
##### Se crea la visualización de datos
library(wordcloud)
## Warning: package 'wordcloud' was built under R version 4.2.3
## Loading required package: RColorBrewer
# Crear la nube de palabras
# se van a plotear los términos comunes (base) que aparecen mínimo de 20 veces y máximo 200.
wordcloud(names(terminos_comunes_limpio), terminos_comunes_limpio, min.freq = 20, max.words = 40, random.order = FALSE, rot.per = 0.25, colors = brewer.pal(8, "Dark2"))
##### Análisis de sentimientos
#Análisis de sentimiento
library(ggplot2)
library(dplyr)
library(tidytext)
corpus_vector_2 <- unlist(sapply(corpus_limpio , as.character))
#Análisis de sentimiento con el paquete nrc,asigna etiquetas de sentimiento (por ejemplo, positivo, negativo o neutro) a palabras en un texto basándose en un conjunto de datos predefinido que asocia palabras con emociones o sentimientos específicos. Finalmente, contamos los sentimientos utilizando count().
archivos.gob <- data.frame(text = corpus_vector_2) %>%
unnest_tokens(word, text) %>%
inner_join(get_sentiments("nrc")) %>%
count(sentiment)
## Joining with `by = join_by(word)`
## Warning in inner_join(., get_sentiments("nrc")): Detected an unexpected many-to-many relationship between `x` and `y`.
## ℹ Row 266 of `x` matches multiple rows in `y`.
## ℹ Row 9377 of `y` matches multiple rows in `x`.
## ℹ If a many-to-many relationship is expected, set `relationship =
## "many-to-many"` to silence this warning.
# Suponiendo que archivos,gob tiene columnas 'sentiment' y 'n'
ggplot(archivos.gob, aes(x = sentiment, y = n, fill = sentiment)) +
geom_bar(stat = "identity") +
labs(title = "Distribución de sentimientos en artículos relacionados a la diversidad corporal en el sitio web de la Secretaría de Gobernación de México (2021) ",
x = "Sentimiento", y = "Cantidad") +
scale_fill_brewer(palette = "Set3") + # Puedes elegir otra paleta de colores
theme_minimal() +
guides(fill = FALSE) # Esto elimina la leyenda de la paleta de colores
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
# Crear una gráfica de pastel para visualizar los sentimientos (Análisis Bing)
library(scales)
##
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
##
## discard
## The following object is masked from 'package:readr':
##
## col_factor
# Calcular los porcentajes
archivos.gob <- archivos.gob %>%
mutate(percentage = n / sum(n) * 100)
# Crear la gráfica de pastel con porcentajes
ggplot(archivos.gob, aes(x = "", y = n, fill = sentiment)) +
geom_bar(stat = "identity", width = 1) +
coord_polar(theta = "y") +
labs(title = "Distribución de Sentimientos en artículos relacionados a la diversidad corporal en el sitio web de la Secretaría de Gobernación de México 2021",
fill = "Sentimiento") +
scale_fill_manual(values = mis_colores) +
theme_minimal() +
theme(axis.title = element_blank(),
axis.text = element_blank(),
legend.position = "bottom") +
geom_text(aes(label = sprintf("%.1f%%", percentage)),
position = position_stack(vjust = 0.5), color = "#3C3333", size = 3) +
theme(plot.title = element_text(face = "bold", hjust = 0.5))