Análisis de texto con frecuencia de término para las novelas de Mark Twain


Introducción

Samuel Langhorne Clemens, también conocido como Mark Twain, es uno de los escritores estadounidenses más importantes. «Las aventuras de Tom Sawyer» es probablemente uno de mis libros favoritos de toda la literatura inglesa. Feliz de ver que las novelas de Twain siguen siendo una lectura obligatoria para los jóvenes estudiantes, ¡ahora se leen más que nunca!

Proyecto Gutenberg ofrece más de 53,000 libros gratis. Usaré cuatro de las mejores novelas de Twain para este análisis:

  • Pasando fatigas
  • La vida en el Mississippi
  • Las aventuras de Tom Sawyer
  • Aventuras de Huckleberry Finn

Utilizaremos los siguientes paquetes para el análisis:

library ( tidyverse ) 
 library ( tidyr ) 
 library ( ggplot2 )  
 library ( tidytext ) 
 library ( stringr ) 
 library ( dplyr ) 
 library ( tm ) 
 library ( topicmodels ) 
 library ( gutenbergr ) 
 theme_set ( theme_minimal ())

Preprocesamiento de datos

Recuperaremos estos cuatro libros usando el paquete gutenbergr:

books   <-   gutenberg_download ( c ( 3177 ,   245 ,   74 ,   76 ),   meta_fields   =   "title" )

Un paso importante de preprocesamiento es la tokenización. Este es el proceso de dividir un texto en palabras individuales o secuencias de palabras. La función unnest_tokens es una forma de hacer precisamente eso. El resultado es convertir la columna de texto en un token-per-row así:

tidy_books   <-   books   %>% 
   unnest_tokens ( word ,   text ) 

 tidy_books
### A tibble: 502,799 x 3 ## gutenberg_id title word ## ## 1 74 The Adventures of Tom Sawyer the ## 2 74 The Adventures of Tom Sawyer adventures ## 3 74 The Adventures of Tom Sawyer of ## 4 74 The Adventures of Tom Sawyer tom ## 5 74 The Adventures of Tom Sawyer sawyer ## 6 74 The Adventures of Tom Sawyer by ## 7 74 The Adventures of Tom Sawyer mark ## 8 74 The Adventures of Tom Sawyer twain ## 9 74 The Adventures of Tom Sawyer samuel ##10 74 The Adventures of Tom Sawyer langhorne # ... with 502,789 more rows ### A tibble: 502,799 x 3 ## gutenberg_id title word ## ## 1 74 The Adventures of Tom Sawyer the ## 2 74 The Adventures of Tom Sawyer adventures ## 3 74 The Adventures of Tom Sawyer of ## 4 74 The Adventures of Tom Sawyer tom ## 5 74 The Adventures of Tom Sawyer sawyer ## 6 74 The Adventures of Tom Sawyer by ## 7 74 The Adventures of Tom Sawyer mark ## 8 74 The Adventures of Tom Sawyer twain ## 9 74 The Adventures of Tom Sawyer samuel ##10 74 The Adventures of Tom Sawyer langhorne # ... with 502,789 more rows

Después de eliminar las stop_words, podemos encontrar las palabras más comunes en los cuatro libros en conjunto.

data ( "stop_words" ) 
 cleaned_books   <-   tidy_books   %>% 
   anti_join ( stop_words ) 

 cleaned_books   %>% 
   count ( word ,   sort   =   TRUE )
### A tibble: 21,630 x 2 ## word n ## ## 1 time 1215 ## 2 tom 982 ## 3 day 701 ## 4 river 684 ## 5 night 562 ## 6 hundred 490 ## 7 water 483 ## 8 head 471 ## 9 chapter 465 ##10 people 461 # ... with 21,620 more rows ### A tibble: 21,630 x 2 ## word n ## ## 1 time 1215 ## 2 tom 982 ## 3 day 701 ## 4 river 684 ## 5 night 562 ## 6 hundred 490 ## 7 water 483 ## 8 head 471 ## 9 chapter 465 ##10 people 461 # ... with 21,620 more rows

Sentimiento

El análisis de sentimientos no sigue el enfoque de hoy, pero como ya estamos aquí, ¿por qué no echar un vistazo rápido?

bing   <-   get_sentiments ( "bing" ) 
 bing_word_counts   <-   tidy_books   %>% 
   inner_join ( bing )   %>% 
   count ( word ,   sentiment ,   sort   =   TRUE )   %>% 
   ungroup () 

 bing_word_counts
### A tibble: 3,023 x 3 ## word sentiment n ## ## 1 well positive 989 ## 2 like positive 856 ## 3 good positive 751 ## 4 right positive 566 ## 5 great positive 427 ## 6 enough positive 367 ## 7 dead negative 344 ## 8 work positive 311 ## 9 pretty positive 280 ##10 better positive 244 # ... with 3,013 more rows ### A tibble: 3,023 x 3 ## word sentiment n ## ## 1 well positive 989 ## 2 like positive 856 ## 3 good positive 751 ## 4 right positive 566 ## 5 great positive 427 ## 6 enough positive 367 ## 7 dead negative 344 ## 8 work positive 311 ## 9 pretty positive 280 ##10 better positive 244 # ... with 3,013 more rows
bing_word_counts   %>% 
   filter ( n   >   100 )   %>% 
   mutate ( n   =   ifelse ( sentiment   ==   'negative' ,   - n ,   n ))   %>% 
   mutate ( word   =   reorder ( word ,   n ))   %>% 
   ggplot ( aes ( word ,   n ,   fill   =   sentiment ))   + 
   geom_bar ( stat   =   'identity' )   + 
   theme ( axis.text.x   =   element_text ( angle   =   90 ,   hjust   =   1 ))   + 
   ylab ( 'Contribution to sentiment' )   +   ggtitle ( 'Most common positive and negative words' )

twain-1

No detectamos anomalías en los resultados del análisis de sentimientos, excepto que la palabra «miss» se identifica como una palabra negativa; en realidad, se usa como título para la vieja y difícil solterona Watson en «Adventures of Huckleberry Finn».

tf-idf

Para citar descaradamente el artículo de Wikipedia en tf-idf:

En el análisis de texto, tf-idf, abreviatura de la frecuencia del documento de frecuencia inversa, es una estadística numérica que pretende reflejar la importancia de una palabra para un documento en una colección o corpus. A menudo se utiliza como factor de ponderación en la recuperación de información y la minería de texto.

Para nuestro propósito, queremos saber las palabras más importantes (tf-idf más altas) en los cuatro libros de Mark Twain en general, y las palabras más importantes (tf-idf más altas) en cada uno de estos cuatro libros. Vamos a averiguar.

book_words   <-   cleaned_books   %>% 
   count ( title ,   word ,   sort   =   TRUE )   %>% 
   ungroup () 

 total_words   <-   book_words   %>%  
   group_by ( title )   %>%  
   summarize ( total   =   sum ( n )) 

 book_words   <-   left_join ( book_words ,   total_words ) 

 book_words
### A tibble: 38,346 x 4 ## title word n total ## ## 1 The Adventures of Tom Sawyer tom 722 24977 ## 2 Life on the Mississippi river 486 51875 ## 3 Life on the Mississippi time 355 51875 ## 4 Adventures of Huckleberry Finn jim 351 32959 ## 5 Roughing It time 344 62611 ## 6 Adventures of Huckleberry Finn time 325 32959 ## 7 Roughing It day 300 62611 ## 8 Adventures of Huckleberry Finn warn't 290 32959 ## 9 Adventures of Huckleberry Finn de 252 32959 ##10 Life on the Mississippi water 245 51875 # ... with 38,336 more rows ### A tibble: 38,346 x 4 ## title word n total ## ## 1 The Adventures of Tom Sawyer tom 722 24977 ## 2 Life on the Mississippi river 486 51875 ## 3 Life on the Mississippi time 355 51875 ## 4 Adventures of Huckleberry Finn jim 351 32959 ## 5 Roughing It time 344 62611 ## 6 Adventures of Huckleberry Finn time 325 32959 ## 7 Roughing It day 300 62611 ## 8 Adventures of Huckleberry Finn warn't 290 32959 ## 9 Adventures of Huckleberry Finn de 252 32959 ##10 Life on the Mississippi water 245 51875 # ... with 38,336 more rows

Términos con el tf-idf más alto en las cuatro novelas

book_words   <-   book_words   %>% 
   bind_tf_idf ( word ,   title ,   n ) 

 book_words   %>% 
   select ( - total )   %>% 
   arrange ( desc ( tf_idf ))
### A tibble: 38,346 x 6 ## title word n tf idf tf_idf ## ## ## 1 The Adventures of Tom Sawyer becky 102 0.004083757 0.6931472 0.002830645 ## 2 The Adventures of Tom Sawyer tom's 97 0.003883573 0.6931472 0.002691888 ## 3 The Adventures of Tom Sawyer huck 232 0.009288545 0.2876821 0.002672148 ## 4 AdventuresofHuckleberry Finn warn't290 0.008798811 0.2876821 0.002531260 ## 5 Life on the Mississippi pilots 93 0.001792771 1.3862944 0.002485308 ## 6 AdventuresofHuckleberry Finn dey 59 0.001790103 1.3862944 0.002481609 ## 7 The Adventures of Tom Sawyer potter 44 0.001761621 1.3862944 0.002442125 ## 8 AdventuresofHuckleberry Finn de 252 0.007645863 0.2876821 0.002199578 ## 9 Roughing It don't 98 0.001565220 1.3862944 0.00216985 ##10 The Adventures of Tom Sawyer sid 77 0.003082836 0.6931472 0.002136859 ### ... with 38,336 more rows ### A tibble: 38,346 x 6 ## title word n tf idf tf_idf ## ## ## 1 The Adventures of Tom Sawyer becky 102 0.004083757 0.6931472 0.002830645 ## 2 The Adventures of Tom Sawyer tom's 97 0.003883573 0.6931472 0.002691888 ## 3 The Adventures of Tom Sawyer huck 232 0.009288545 0.2876821 0.002672148 ## 4 AdventuresofHuckleberry Finn warn't290 0.008798811 0.2876821 0.002531260 ## 5 Life on the Mississippi pilots 93 0.001792771 1.3862944 0.002485308 ## 6 AdventuresofHuckleberry Finn dey 59 0.001790103 1.3862944 0.002481609 ## 7 The Adventures of Tom Sawyer potter 44 0.001761621 1.3862944 0.002442125 ## 8 AdventuresofHuckleberry Finn de 252 0.007645863 0.2876821 0.002199578 ## 9 Roughing It don't 98 0.001565220 1.3862944 0.00216985 ##10 The Adventures of Tom Sawyer sid 77 0.003082836 0.6931472 0.002136859 ### ... with 38,336 more rows ### A tibble: 38,346 x 6 ## title word n tf idf tf_idf ## ## ## 1 The Adventures of Tom Sawyer becky 102 0.004083757 0.6931472 0.002830645 ## 2 The Adventures of Tom Sawyer tom's 97 0.003883573 0.6931472 0.002691888 ## 3 The Adventures of Tom Sawyer huck 232 0.009288545 0.2876821 0.002672148 ## 4 AdventuresofHuckleberry Finn warn't290 0.008798811 0.2876821 0.002531260 ## 5 Life on the Mississippi pilots 93 0.001792771 1.3862944 0.002485308 ## 6 AdventuresofHuckleberry Finn dey 59 0.001790103 1.3862944 0.002481609 ## 7 The Adventures of Tom Sawyer potter 44 0.001761621 1.3862944 0.002442125 ## 8 AdventuresofHuckleberry Finn de 252 0.007645863 0.2876821 0.002199578 ## 9 Roughing It don't 98 0.001565220 1.3862944 0.00216985 ##10 The Adventures of Tom Sawyer sid 77 0.003082836 0.6931472 0.002136859 ### ... with 38,336 more rows
plot   <-   book_words   %>% 
   arrange ( desc ( tf_idf ))   %>% 
   mutate ( word   =   factor ( word ,   levels   =   rev ( unique ( word )))) 

 plot   %>%  
   top_n ( 20 )   %>% 
   ggplot ( aes ( word ,   tf_idf ,   fill   =   title ))   + 
   geom_bar ( stat   =   'identity' ,   position   =   position_dodge ()) + 
   labs ( x   =   NULL ,   y   =   "tf-idf" )   + 
   coord_flip ()   +   ggtitle ( "Top tf-idf words in Mark Twain's Four Novels" )

twain-2

plot   %>%  
   group_by ( title )   %>%  
   top_n ( 10 )   %>%  
   ungroup   %>% 
   ggplot ( aes ( word ,   tf_idf ,   fill   =   title ))   + 
   geom_col ( show.legend   =   FALSE )   + 
   labs ( x   =   NULL ,   y   =   "tf-idf" )   + 
   facet_wrap ( ~ title ,   ncol   =   2 ,   scales   =   "free" )   + 
   coord_flip ()   +   ggtitle ( 'Top tf-idf words in each novel' )

twain-3

Cada novela tiene sus propias palabras tf-idf más altas. Sin embargo, el lenguaje que usó en estas cuatro novelas es bastante similar, como el término «ciudad» tiene un alto índice de idf en «Roughing it» y «Life on the Mississippi».

Frecuencia de término

Comparemos las obras de Mark Twain con las de Charles Dicken. Consigamos “Un cuento de dos ciudades”, “Grandes expectativas”, “Un cuento de Navidad en prosa; Siendo una historia fantasma de Navidad ”,“ Oliver Twist ”y“ Tiempos difíciles ”.

¿Cuáles son las palabras más comunes en estas novelas de Charles Dickens?

dickens   <-   gutenberg_download ( c ( 98 ,   1400 ,   46 ,   730 ,   786 )) 
 tidy_dickens   <-   dickens   %>% 
   unnest_tokens ( word ,   text )   %>% 
   anti_join ( stop_words ) 
 tidy_dickens   %>% 
   count ( word ,   sort   =   TRUE )
### A tibble: 19,634 x 2 ## word n ## ## 1 time 1218 ## 2 hand 918 ## 3 night 835 ## 4 looked 814 ## 5 head 813 ## 6 oliver 766 ## 7 dear 751 ## 8 joe 718 ## 9 miss 702 ##10 sir 697 ### ... with 19,624 more rows ### A tibble: 19,634 x 2 ## word n ## ## 1 time 1218 ## 2 hand 918 ## 3 night 835 ## 4 looked 814 ## 5 head 813 ## 6 oliver 766 ## 7 dear 751 ## 8 joe 718 ## 9 miss 702 ##10 sir 697 ### ... with 19,624 more rows
tidy_twains   <-   books   %>% 
   unnest_tokens ( word ,   text )   %>% 
   anti_join ( stop_words ) 

 frequency   <-   bind_rows ( mutate ( tidy_twains ,   author   =   "Mark Twain" ), 
                        mutate ( tidy_dickens ,   author   =   "Charles Dickens" ))   %>%  
   mutate ( word   =   str_extract ( word ,   "[a-z']+" ))   %>% 
   count ( author ,   word )   %>% 
   group_by ( author )   %>% 
   mutate ( proportion   =   n   /   sum ( n ))   %>%  
   select ( - n )   %>%  
   spread ( author ,   proportion )   %>%  
   gather ( author ,   proportion ,   `Mark Twain` : `Charles Dickens` ) 

 frequency $ word   <-   factor ( frequency $ word ,  
                      levels = unique ( with ( frequency ,  
                                  word [ order ( proportion ,   word ,  
                                             decreasing   =   TRUE )]))) 
 frequency   <-   frequency [ complete.cases ( frequency ),   ] 
 ggplot ( aes ( x   =   reorder ( word ,   proportion ),   y   =   proportion ,   fill   =   author ),  
        data   =   subset ( frequency ,   proportion > 0.0025 ))   + 
   geom_bar ( stat   =   'identity' ,   position   =   position_dodge ()) + 
   coord_flip ()   +   ggtitle ( 'Comparing the word frequencies of Mark Twain and Charles Dickens' )

twain-4

El término superior para ambos autores es el mismo: «tiempo». Aparte de eso, su lenguaje es muy diferente.

El análisis de texto con frecuencia temporal para las novelas de Mark Twain fue publicado originalmente por Susan Li en Susan Li | Data Ninja

Anuncio publicitario

Deja una respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Salir /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.