Análisis de Sentimiento en E-commerce
Análisis de Sentimiento en E-commerce
POYECTO FINAL
PRESENTA:
PROFESOR:
Jorge Rodríguez Rubio
Facultad de Ingeniería, UNAM
Contenido
I.- INTRODUCCIÓN. ...................................................................................................................................... 3
2
I.- INTRODUCCIÓN.
Sin embargo, aunque haya empresas mejor preparadas que otras, todas deben
alcanzar el mismo destino y para ello cada una debe encontrar su propio camino. En
2018 el ITRE encargó un estudio para obtener información sobre cómo la Unión
Europea puede aprovechar la oportunidad que plantea el uso de la inteligencia
artificial. Uno de los puntos que trata esta investigación es la aceptación de la IA en las
empresas europeas. En él se refleja que tan sólo un 20 % de las organizaciones usan
esta tecnología actualmente. El porcentaje de pymes es mucho más bajo, únicamente
3
supone un 5 % sobre el total. A continuación, se muestra un gráfico donde se recoge el
porcentaje de empresas que hacen uso de soluciones o servicios de IA:
Las pymes pueden encontrar una magnífica solución para cumplir con sus necesidades
en el Cloud Computing. Los servicios en la nube que ofrecen grandes proveedores
como Google, Microsoft o Amazon ponen al alcance de estas empresas la tecnología
que antes sólo se podían permitir las grandes organizaciones. Además, al ser recursos
completamente gestionados por las empresas proveedoras, las organizaciones
pueden centrarse más en su negocio y abstraerse de la infraestructura o la
disponibilidad de su sistema.
II.- ANTECEDENTES
4
El campo de estudio del análisis de sentimientos o minería de opiniones se ha
convertido en un área de investigación muy activa a partir del año 2000. Antes de
dicho año, se habían realizado escasas investigaciones que no fueron concluyentes
respecto a su eficacia.
Fueron Nasukawa y Yi en 2003 los que utilizaron por primera vez el término análisis
de sentimientos en su trabajo sobre una técnica de extracción de sentimientos
asociados con polaridades positivas o negativas (polaridad, también conocida como
orientación, es la emoción expresada en la oración), para temas específicos de un
documento, y el término minería de opiniones, apareció por primera vez publicado en
las actas de la conferencia de la World Wide Web de 2003 por Dave et al. (2003), en
las cuales se propone una herramienta para procesar conjuntos de resultados de
búsqueda para un ítem específico, con el fin de obtener sus características y poder
valorarlas positiva o negativamente.
5
Figura 2- Clasificación de los algoritmos más populares del Machine Learning
6
(clustering, en inglés), que tienen como objetivo intentar encontrar patrones de
similitud en los textos y agruparlos por sus características comunes. Ejemplos de
algoritmo de agrupamiento son el clasificador jerárquico y modelos de mezclas
gaussianas (Liu, 2010).
Para ilustrar lo anteriormente dicho caben destacar algunos trabajos sobre el análisis
de sentimientos relacionados con el desarrollo de las redes sociales como el de Asur y
Huberman (2010), en el que se propone un nuevo procedimiento para calcular la
polaridad de un corpus de mensajes de Twitter, con el propósito de averiguar si la
taquilla de los próximos estrenos cinematográficos tendrá éxito o no. La idea es
recoger automáticamente los mensajes publicados sobre una determinada película y
asignar un peso positivo, negativo o neutro a determinadas palabras que expresan
opinión o sentimiento. Posteriormente, para cada mensaje, se calcula su polaridad
mediante la suma total de los pesos individuales de las palabras del texto del mensaje.
Así mismo, trabajos más recientes, como por ejemplo el de Kiritchenko et al. (2014),
en el cual se describe un sistema de análisis de sentimientos de última generación que
detecta el sentimiento de los mensajes de texto informales, en particular tweets y
mensajes SMS, los evalúa y los clasifica. Esta tarea se lleva a cabo a través un sistema
supervisado que se basa en un enfoque de aprendizaje automático empleando léxicos
generados automáticamente usando tweets con hashtags y tweets con emoticonos
precedentemente clasificados. Estos ejemplos de trabajos son una muestra del tipo de
estrategias, herramientas y recursos utilizados actualmente para el análisis
automático de opinión.
III.- PROBLEMÁTICA.
A pesar de que hoy en día se cuenta con la tecnología necesaria para realizar el análisis
de sentimientos, la mayoría de las pymes aun no hacen uso de esta tecnología para
explotar los datos de sus clientes o de empresas que tengan sus datos abiertos a todo
publico y que puedan explotarse, además a partir de ello se puede obtener una ventaja
competitiva en el mercado. La baja demanda en estas empresas se piensa que es
7
debido a que se tiene una idea errónea de que es muy costosa o laboriosa la
implementación.
Objetivo Principal
• Realizar un desarrollo para mostrar que es posible realizar una integración low
cost de análisis de sentimientos que pueda ser escalable y nos ayude en la toma
de decisiones.
Objetivos Específicos
8
V.- ESTADO DEL ARTE
Actualmente, resulta muy sencillo enseñar a una IA a ganar una partida de ajedrez, en
cambio, el reto está en conseguir que pueda emular un sistema tan complejo como la
mente humana. Como dijo Alan Winfield, profesor de robótica en la UWE (Bristol):
"Hoy en día hemos aceptado que, 60 años más tarde del nacimiento de la IA, las cosas
que originalmente asumíamos como fáciles, en realidad han resultado ser muy difíciles
y lo que pensábamos que era difícil, como jugar al ajedrez, es en realidad muy fácil".
Los científicos llevan muchos años intentando imitar la mente humana mediante
sistemas "inteligentes". Desde que John McCarthy y Marvin Minsky fundaran la
Inteligencia Artificial en 1956 se han conseguido resultados, inimaginables en ese
entonces, que han demostrado la utilidad social, intelectual y cultural que tiene para
la sociedad esta tecnología.
Para las máquinas, al igual que el ser humano, resulta más sencillo obtener información
sobre las emociones a partir de un vídeo o una conversación hablada. El análisis de
sentimientos, un subcampo del procesamiento del lenguaje natural se ocupa de
identificar opiniones, emociones y evaluaciones positivas o negativas respecto a
diferentes temas. En este sentido la Inteligencia Artificial tiene una serie de obstáculos
por delante, ya que, la comunicación humana va acompañada de principios difíciles de
recrear artificialmente como son el humor, los dobles sentidos, la ironía o los
sentimientos que añade el comunicador.
9
Algunas de éstas se han centrado en el análisis de opiniones sobre productos y
películas (Hu y Liu, 2004; Popescu y Etzioni, 2005). Estos textos cuentan con la ventaja
de que ya tienen un tema claramente especificado. Muchos investigadores también
han analizado las opiniones públicas durante una campaña electoral, como Chung y
Mustafaraj (2011) y Gayo-Avello et al. (2011) que discuten sobre las limitaciones de
utilizar datos obtenidos de Twitter para predecir las elecciones políticas. Otra área
popular de aplicación es la predicción del mercado de valores. Por ejemplo, Zhang et
al. (2010) identifica estados de ánimo positivos y negativos en Twitter y hace uso de
esta información para predecir el movimiento de los índices bursátiles.
Conceptos
Problemas y Limitaciones
10
a) La dificultad para establecer una escala objetiva para describir la polaridad de
sentimientos y opiniones. Las dificultades están fundamentalmente en que: no
todas las palabras tienen un significado preciso por lo que puede resultar difícil
clasificarlos como totalmente positivos o negativos; y, en que para establecer
objetivamente la polaridad a nivel léxico es necesario resolver cómo calcularla
en los distintos niveles del texto: frase, párrafo, sección, etc. (Liu, 2010).
11
f) La aparición, en una misma frase, de una opinión o sentimiento positivo y otro
negativo. Detectar ambas opiniones es un reto bastante complicado para el
análisis de sentimientos, pero se dispone de algunas técnicas específicas como
el resumen comparativo de opiniones contrastadas (COS por su sigla en inglés)
que extrae frases comparables de cada conjunto de opiniones y generar una
síntesis comparativa con los pares de frases contrastadas (Kim y Zhai, 2009).
En definitiva, estos son algunos de los retos del análisis de sentimientos. Son las
razones por las cuales las herramientas actuales no logran trabajar con una
precisión del 100%.
Tipos de Análisis
Las ventajas del análisis de sentimiento sin numerosas, aquí mostraremos las más
relevantes:
12
• Permite mantenerte al tanto de lo que le gusta y de lo que no les gusta a los
consumidores de tus productos y servicios.
• Permite enfocarte en los diferentes segmentos del mercado y crear productos
y servicios que los atraigan.
• Favorece el análisis de las revisiones o de la retroalimentación del cliente y
compararlos con la competencia para comprender en qué puntos hay que
realizar mejoras.
• Ayuda a abordar rápidamente los problemas que enfrentan los clientes al usar
tus productos o servicios.
• Favorece la reputación de la marca y la percepción de los clientes.
• Ayuda a comprender el estado de ánimo de los clientes, así como los efectos
que ocurren alrededor de las opiniones de los clientes a lo largo del tiempo.
13
En la siguiente tabla se especifican las etapas de este trabajo, así como los entregables
esperados en cada uno:
# Etapa Entregable
1 Extracción de la información Base input
2 Análisis de la información Código con EDA e
ingeniería de
características
3 Desarrollo Modelo y base output
4 Visualización Tablero de control
• Polaridad
• EDA
• Nube de Tablero de
Extracción Base input Análisis • Ingenieria de Desarrollo Visualización
Palabras Control
Caracteristicas
• Base Output
Figura 3.- Esquema del flujo de información y las etapas del proyecto.
14
VIII.- REFERENCIAS.
• Amarouche, K., Benbrahim, H., & Kassou, I. (2015). Product opinion mining for
competitive intelligence. Proceedings of the Computer Science, 73, 358–365.
• Asur, S., & Huberman, B. (2010). Predicting the future with social media.
International. Conference on Web Intelligence and Intelligent Agent
Technology (WIIAT), 1, 492-499.
• R. Kats, “Retail sales in spain will fall nearly 13 % in 2020, the biggest drop in
western europe,” Recuperado 4 agosto 2020
[Link]
2020-biggest-drop-western-europe, 12 julio 2020.
15
Proyecto Final Big Data
1
packages (from httpx==0.13.3->googletrans==4.0.0-rc1) (2.10)
Requirement already satisfied: h2==3.* in /usr/local/lib/python3.8/dist-packages
(from httpcore==0.9.*->httpx==0.13.3->googletrans==4.0.0-rc1) (3.2.0)
Requirement already satisfied: h11<0.10,>=0.8 in /usr/local/lib/python3.8/dist-
packages (from httpcore==0.9.*->httpx==0.13.3->googletrans==4.0.0-rc1) (0.9.0)
Requirement already satisfied: hpack<4,>=3.0 in /usr/local/lib/python3.8/dist-
packages (from h2==3.*->httpcore==0.9.*->httpx==0.13.3->googletrans==4.0.0-rc1)
(3.0.0)
Requirement already satisfied: hyperframe<6,>=5.2.0 in
/usr/local/lib/python3.8/dist-packages (from
h2==3.*->httpcore==0.9.*->httpx==0.13.3->googletrans==4.0.0-rc1) (5.2.0)
[193]: True
2
[195]: # La data fue extraida de una pagina de videojuegos en linea [Link]
'''
El dataset, es una muestra de diferentes reseñas del videojuego GoW Ragnarok,␣
,→las columnas son las siguientes:
'''
# Carga de la data
ruta = '/content/drive/MyDrive/'
archivo = "GOW_revieW_Fin.xlsx"
archivo_out = "Review_Tableau.xlsx"
gow = pd.read_excel(path)
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness
0 21\nof \n27\nusers found this helpful
1 20\nof \n26\nusers found this helpful
2 19\nof \n25\nusers found this helpful
3 19\nof \n25\nusers found this helpful
4 17\nof \n23\nusers found this helpful
3
[196]: # Validar los tipos de dato
[Link]
[Link]
[198]: (170, 5)
[199]: (106, 5)
[Link]()
[200]: Rating
count 106.000000
mean 8.141509
std 3.127265
min 0.000000
25% 7.000000
50% 10.000000
75% 10.000000
max 10.000000
4
[201]: Rating Name Date \
0 10 ARMENHAMMER18 2022-11-13
1 10 Atres 2022-11-13
2 10 stipex 2022-11-12
3 10 Exc-Enthusiast 2022-11-11
4 10 Darkula666 2022-11-13
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
def text_cleaner(x):
text=[Link]("[@&][A-Za-z0-9_]+","", x) # Remover caracteres
text=[Link](r"http\S+","", text) # Remover links
return [Link]([text])
gow[['plain_text']] = [Link](text_cleaner)
[Link]()
5
[202]: Rating Name Date \
0 10 ARMENHAMMER18 2022-11-13
1 10 Atres 2022-11-13
2 10 stipex 2022-11-12
3 10 Exc-Enthusiast 2022-11-11
4 10 Darkula666 2022-11-13
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text
0 just simply a masterpiece. don't know how they…
1 , click expand to view|o jogo em si é uma evol…
2 , click expand to view|dawno się tak dobrze ni…
3 , click expand to view|the best game i've ever…
4 wow. just one of the most perfect sequels, hon…
def detect_textlang(text):
try:
src_lang = detect(text)
if src_lang =='en':
return 'en'
else:
#return "NA"
return src_lang
except:
return "NA"
gow['text_idiom'] = gow.plain_text.apply(detect_textlang)
[Link]()
6
3 10 Exc-Enthusiast 2022-11-11
4 10 Darkula666 2022-11-13
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
[Link](figsize=(4,3))
[Link](gow.text_idiom).plain_text.count().sort_values(ascending=False).
,→head(10).[Link]()
[Link]()
7
Como podemos observar la mayoria de los comentarios estan en inglés, por lo cual para homologar,
haremos traduccion de los textos a este idioma
def translate_text(lang,text):
translator= Translator()
trans_text = [Link](text, src=lang).text
return trans_text
gow.Translated_text = gow.Translated_text.[Link]()
[206]: [Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text
8
0 just simply a masterpiece. don't know how they…
1 , click expand to view | the game itself is an…
2 , click expand to view | i haven't had so much…
3 , click expand to view|the best game i've ever…
4 wow. just one of the most perfect sequels, hon…
gow["Count_Words"] = gow['Translated_text'].[Link]().[Link]()
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
9
[208]: # Creamos una columna que elimine las "stop_words"
gow['Text_Without_Stop_Words'] = gow['Translated_text'].apply(lambda x: ' '.
,→join([word for word in [Link]() if word not in (stop)]))
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
10
[209]: # Creamos una columna que elimine los signos de puntuación
gow["Text_Clean"] = gow['Text_Without_Stop_Words'].[Link]('[^\w\s]','')
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
11
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean
0 simply masterpiece know 2018 beat highest expe…
1 click expand view game evolution first innov…
2 click expand view much fun game 29 hours try…
3 click expand viewthe best game ive ever playe…
4 wow one perfect sequels honestly fantastic gam…
gow["Count_Text_Clean"] = gow['Text_Clean'].[Link]().[Link]()
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
12
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean Count_Text_Clean
0 simply masterpiece know 2018 beat highest expe… 23
1 click expand view game evolution first innov… 70
2 click expand view much fun game 29 hours try… 97
3 click expand viewthe best game ive ever playe… 88
4 wow one perfect sequels honestly fantastic gam… 8
[211]: # Como la unica columna númerica es Rating, solo nos aparecio esa columna, sin␣
,→embargo haremos un poco de Feature Enginering
digits = r"\d+"
gow["Digits"] = gow["Usefulness"].[Link](digits)
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
13
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean Count_Text_Clean \
0 simply masterpiece know 2018 beat highest expe… 23
1 click expand view game evolution first innov… 70
2 click expand view much fun game 29 hours try… 97
3 click expand viewthe best game ive ever playe… 88
4 wow one perfect sequels honestly fantastic gam… 8
Digits
0 [21, 27]
1 [20, 26]
2 [19, 25]
3 [19, 25]
4 [17, 23]
gow["Users_Usefulness_Review"] = gow["Digits"].str[0]
[Link]()
14
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean Count_Text_Clean \
0 simply masterpiece know 2018 beat highest expe… 23
1 click expand view game evolution first innov… 70
2 click expand view much fun game 29 hours try… 97
3 click expand viewthe best game ive ever playe… 88
4 wow one perfect sequels honestly fantastic gam… 8
Digits Users_Usefulness_Review
0 [21, 27] 21
1 [20, 26] 20
2 [19, 25] 19
3 [19, 25] 19
15
4 [17, 23] 17
gow["Users_Total_Review"] = gow["Digits"].str[1]
[Link]()
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
16
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean Count_Text_Clean \
0 simply masterpiece know 2018 beat highest expe… 23
1 click expand view game evolution first innov… 70
2 click expand view much fun game 29 hours try… 97
3 click expand viewthe best game ive ever playe… 88
4 wow one perfect sequels honestly fantastic gam… 8
gow["Users_Usefulness_Review"] = gow["Users_Usefulness_Review"].astype(int)
gow["Users_Total_Review"] = gow["Users_Total_Review"].astype(int)
Text \
0 Just simply a masterpiece. Don't know how they…
1 , click expand to view|O jogo em si é uma evol…
2 , click expand to view|Dawno się tak dobrze ni…
3 , click expand to view|The best game I've ever…
4 Wow. Just one of the most perfect sequels, hon…
Usefulness id_row \
0 21\nof \n27\nusers found this helpful 2022-11-13ARMENHAMMER18
1 20\nof \n26\nusers found this helpful 2022-11-13Atres
2 19\nof \n25\nusers found this helpful 2022-11-12stipex
3 19\nof \n25\nusers found this helpful 2022-11-11Exc-Enthusiast
4 17\nof \n23\nusers found this helpful 2022-11-13Darkula666
plain_text text_idiom \
17
0 just simply a masterpiece. don't know how they… en
1 , click expand to view|o jogo em si é uma evol… pt
2 , click expand to view|dawno się tak dobrze ni… pl
3 , click expand to view|the best game i've ever… en
4 wow. just one of the most perfect sequels, hon… en
Translated_text Count_Words \
0 just simply a masterpiece. don't know how they… 49
1 , click expand to view | the game itself is an… 134
2 , click expand to view | i haven't had so much… 209
3 , click expand to view|the best game i've ever… 142
4 wow. just one of the most perfect sequels, hon… 13
Text_Without_Stop_Words \
0 simply masterpiece. know 2018 beat highest exp…
1 , click expand view | game evolution first, in…
2 , click expand view | much fun game 29 hours t…
3 , click expand view|the best game i've ever pl…
4 wow. one perfect sequels, honestly fantastic g…
Text_Clean Count_Text_Clean \
0 simply masterpiece know 2018 beat highest expe… 23
1 click expand view game evolution first innov… 70
2 click expand view much fun game 29 hours try… 97
3 click expand viewthe best game ive ever playe… 88
4 wow one perfect sequels honestly fantastic gam… 8
[Link]()
18
Users_Total_Review Ratio_Review
count 106.000000 104.000000
mean 15.226415 0.675051
std 32.897325 0.189031
min 0.000000 0.000000
25% 3.000000 0.600000
50% 6.000000 0.666667
75% 12.500000 0.750000
max 255.000000 1.000000
[216]: #INTERACTIVA
#Crreación función con un for que recorra todas las variables numerocas del df␣
,→y nos muestre su histograma, percentiles y datos relevantes
@interact
def stats_vars(bins = [10,20,30,40,50,60,70,80,90,100],
facecolor = ['grey','lightblue','orange','green','red']
):
print('-------------------------------------------- VARIABLES␣
,→NUMERICAS-------------------------------------------------------')
var_num = numericas
cont = 1
for c in var_num:
print('\n///////////////////////////////////////',cont,")",c,'//////////
,→//////////////////////////////////////////////////')
gow[c] = gow[c].astype(float)
#N° de vacíos
print('N° nulos:', [Link][gow[c].isna()==True].shape[0])
# contar el número de categorías únicas
num_cat = len(gow[c].unique())
cont += 1
print('N° de valores distintos:', num_cat)
19
g_aux.rename(columns={c : 'Porcentaje'}, inplace=True)
g_aux.reset_index(inplace=True)
g_aux.rename(columns={'index' : c}, inplace=True)
display(g_aux)
[Link](' '.join(gow.Text_Clean))
[Link](figsize=(10,12))
[Link](wc, interpolation="bilinear")
[Link]("off")
20
1.3.1 Análisis de Sentimientos
La clase SentimentIntensityAnalyzer() utiliza el diccionario Valence Aware y el sEntiment Reasoner
(VADER) en NLTK. El léxico de sentimientos en VADER es una lista de características léxicas
como palabras y frases etiquetadas como positivas o negativas según su orientación semántica. Su
enfoque basado en reglas es especialmente bueno para detectar opiniones en aplicaciones comunes
como publicaciones en redes sociales, reseñas de productos o servicios y respuestas a encuestas.
VADER también genera una puntuación numérica en el rango de uno negativo (-1) a uno positivo
(+1) para indicar la intensidad de cuán negativo o positivo es el sentimiento. Esto se denomina
puntaje de polaridad y se implementa mediante el método polarity_score de la clase SentimentIn-
tensityAnalyzer.
• La puntuación de polaridad en el rango de -1 a -0.5 generalmente indica un sentimiento
negativo
• La puntuación de polaridad superior a -0,5 e inferior a +0,5 suele indicar un sentimiento
neutral
• La puntuación de polaridad en el rango de +0,5 a 1 generalmente indica un sentimiento
positivo
Los siguientes pasos implican crear una instancia de un objeto de la clase SentimentIntensityAna-
lyzery ejecutar un ciclo for para iterar el polarity_scoresmétodo sobre cada fila del marco de datos
de texto de entrada df_subset. Otro bucle for está incrustado con el bucle anterior para escribir
la puntuación de polaridad del sentimiento para cada tipo de sentimiento en un marco de datos
intermedio. Los tres valores de tipo de sentimiento son.
• neg para sentimiento negativo
• neu para sentimiento neutral
• pos para sentimiento positivo
21
• compound para un puntaje general que combina sentimientos negativos, positivos y neutrales
en un solo puntaje.
"""
Para nuestro caso de estudio consideraremos que:
def get_sentiment(polarity):
if polarity < 0.0:
return 'Negativo'
elif polarity > 0.2:
return 'Positivo'
else:
return 'Neutral'
# Graficar la polaridad
gow['Sentiment'] = [Link](get_sentiment)
[Link](figsize=(3,3))
[Link].value_counts().[Link]()
22
[220]: [Link]
[Link](' '.join(gow_neg.Text_Clean))
[Link](figsize=(10,12))
[Link](wc, interpolation="bilinear")
[Link]("off")
23
wc=WordCloud(stopwords=stop, collocations=False, max_font_size=55,␣
,→max_words=25, background_color="black")
[Link](' '.join(gow_pos.Text_Clean))
[Link](figsize=(10,12))
[Link](wc, interpolation="bilinear")
[Link]("off")
[Link](' '.join(gow_neu.Text_Clean))
[Link](figsize=(10,12))
[Link](wc, interpolation="bilinear")
[Link]("off")
24
[225]: # Crear Excel de Salida que sera la entrada del tablero de control de Tableau
out = gow.to_excel(path_out)
1.4 Conclusiones
• Se logro crear un script en un lenguaje open source, escalable y fácil de implementar que si
bien solo recibio en esta ocacion 170 registros podria procesar muchisimos más registros en
cada ejecución.
• El script es capaz de detectar el idioma del comentario y taducirlo al ingles para posteri-
ormente hacer el análisis de sentimiento y valuar la polaridad de los comentarios de cada
usuario.
• Realizamos ingenieria de caracteristicas en el script para dar como salida una base con más
columnas que servira para usar en el tablero y generar visualizaciones más potentes.
25