Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,127 +1,128 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
nltk
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
stop_words.
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
plt.
|
| 41 |
-
plt.
|
| 42 |
-
plt.
|
| 43 |
-
|
| 44 |
-
st.
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
ax.
|
| 55 |
-
|
| 56 |
-
plt.
|
| 57 |
-
plt.
|
| 58 |
-
plt.
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
materias
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
ax.
|
| 85 |
-
ax.
|
| 86 |
-
ax.
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
#
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
st.
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
st.
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
| 1 |
+
!pip install nltk
|
| 2 |
+
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from collections import Counter
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import numpy as np
|
| 7 |
+
import re
|
| 8 |
+
import json
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import nltk
|
| 11 |
+
nltk.download('stopwords')
|
| 12 |
+
from wordcloud import WordCloud
|
| 13 |
+
from nltk.corpus import stopwords
|
| 14 |
+
import spacy
|
| 15 |
+
nlp = spacy.load("es_core_news_sm")
|
| 16 |
+
|
| 17 |
+
def lemmatize_text(text):
|
| 18 |
+
doc = nlp(text)
|
| 19 |
+
lemmatized = ' '.join([token.lemma_ for token in doc if not token.is_stop])
|
| 20 |
+
return lemmatized
|
| 21 |
+
|
| 22 |
+
def clean_text(series):
|
| 23 |
+
# Convertir la serie a una sola cadena de texto
|
| 24 |
+
text = ' '.join(series.dropna().astype(str))
|
| 25 |
+
# Eliminar caracteres no deseados (opcional, pero recomendado)
|
| 26 |
+
text = re.sub(r'[^\w\s]', '', text.lower())
|
| 27 |
+
# Lematizar el texto
|
| 28 |
+
lemmatized_text = lemmatize_text(text)
|
| 29 |
+
# Eliminar stopwords adicionales que no fueron removidas por spaCy
|
| 30 |
+
stop_words = set(stopwords.words('spanish'))
|
| 31 |
+
stop_words.update(["maestro", "clase", "profesor", "doctor", "profe", "alumno", "dr", "doctora", "material", "maestra", "ms", "mejor"])
|
| 32 |
+
words = [word for word in lemmatized_text.split() if word not in stop_words]
|
| 33 |
+
cleaned_text = ' '.join(words)
|
| 34 |
+
return cleaned_text
|
| 35 |
+
|
| 36 |
+
# Crear la nube de palabras
|
| 37 |
+
def create_wordcloud_from_series(cleaned_text, escuela):
|
| 38 |
+
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(cleaned_text)
|
| 39 |
+
# Mostrar la nube de palabras
|
| 40 |
+
plt.figure(figsize=(10, 5))
|
| 41 |
+
plt.imshow(wordcloud, interpolation='bilinear')
|
| 42 |
+
plt.axis('off')
|
| 43 |
+
plt.show()
|
| 44 |
+
#st.write(f"Palabras mas utilizadas por los alumnos de {escuela}")
|
| 45 |
+
st.pyplot(plt)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def plot_top_words(words, top_n=20):
|
| 50 |
+
words = words.split(" ")
|
| 51 |
+
word_counts = Counter(words)
|
| 52 |
+
common_words = word_counts.most_common(top_n)
|
| 53 |
+
words, counts = zip(*common_words)
|
| 54 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 55 |
+
ax.bar(words, counts)
|
| 56 |
+
plt.xticks(rotation=90)
|
| 57 |
+
plt.xlabel('Palabras')
|
| 58 |
+
plt.ylabel('Frecuencia')
|
| 59 |
+
plt.title(f'Top {top_n} palabras más usadas')
|
| 60 |
+
st.pyplot(fig)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# cargamos información de Escuelas
|
| 64 |
+
escuelas = pd.read_json('./escuelas.json', orient='records', lines=True).drop(columns = "Unnamed: 0")
|
| 65 |
+
categories = escuelas["Escuela"].unique()
|
| 66 |
+
|
| 67 |
+
# cargamos datos
|
| 68 |
+
datos = pd.read_json('./datos.json', orient='records', lines=True)
|
| 69 |
+
print(datos.columns)
|
| 70 |
+
|
| 71 |
+
def tabla_materias(df):
|
| 72 |
+
# seleccionamos las materias con más comentarios
|
| 73 |
+
materias = df["Class Name"].value_counts().index[:12]
|
| 74 |
+
df_f = df[df["Class Name"].isin(materias)].groupby("Class Name").sentimiento.value_counts(normalize = True).fillna(0).unstack(-1).style.format('{:.2%}')
|
| 75 |
+
return df_f
|
| 76 |
+
|
| 77 |
+
def tabla_anio(df):
|
| 78 |
+
# seleccionamos las materias con más comentarios
|
| 79 |
+
df["year"] = df.Date.dt.year
|
| 80 |
+
df_f = df.groupby(["year"]).sentimiento.value_counts(normalize = True).fillna(0.0).unstack(0).T.reset_index() # .style.format('{:.2%}')
|
| 81 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 82 |
+
for column in ["postivo", "negativo"]:
|
| 83 |
+
ax.plot(df_f['year'], df_f[column], label=column)
|
| 84 |
+
ax.set_xlabel('Year')
|
| 85 |
+
ax.set_ylabel('%')
|
| 86 |
+
ax.set_title('Sentimiento anual por años')
|
| 87 |
+
ax.legend()
|
| 88 |
+
return st.pyplot(fig)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
st.title('Análisis de Sentimiento a comentarios Realizados en MisProfesores.com')
|
| 94 |
+
selected_category = st.selectbox("Seleccionar una Escuela para hacer Web Scrapping", categories)
|
| 95 |
+
datos_f= datos[datos.escuela == selected_category]
|
| 96 |
+
# eliminar al cambiar el dato
|
| 97 |
+
# generamos dos conjuntos de datos para comparar
|
| 98 |
+
datos_positivos = datos_f[datos_f.sentimiento == "postivo"]
|
| 99 |
+
# generamos dos conjuntos de datos para comparar
|
| 100 |
+
datos_negativos = datos_f[datos_f.sentimiento == "negativo"]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
for key, dat in {"positivas": datos_positivos , "negativas": datos_negativos}.items():
|
| 104 |
+
st.header(f"Palabras mas utilizadas por los alumnos con calificaciones {key}")
|
| 105 |
+
# generamos nube de palabras
|
| 106 |
+
cleaned_text = clean_text(dat.Comments)
|
| 107 |
+
create_wordcloud_from_series(cleaned_text, selected_category)
|
| 108 |
+
plot_top_words(cleaned_text, top_n=20)
|
| 109 |
+
|
| 110 |
+
# desplegamos los resultados de las 5 materias mas comunes
|
| 111 |
+
st.header(f"Así es cómo los alumnos de la {selected_category} se sienten a lo largo de los años")
|
| 112 |
+
tabla_anio(datos_f)
|
| 113 |
+
st.write(f"curioso como el porcentaje de sentimientos positivos baja por culpa de la pandemia")
|
| 114 |
+
|
| 115 |
+
st.header(f"estas fueron las calificaciones de las materias más comentadas de {selected_category}")
|
| 116 |
+
st.dataframe( tabla_materias(datos_f))
|
| 117 |
+
|
| 118 |
+
st.write(f"aqui puedes observar los datos por si tienes curiosidad de lo que dicen los usuarios!")
|
| 119 |
+
st.dataframe( datos_positivos)
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
main()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|