Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
@@ -1,398 +0,0 @@
|
|
1 |
-
all_stopwords=['sugl', 'up', 'stetti', 'lei', 'vi', 'ti', 'avait', 'on', 'you', 'tutto', 'nos', 'ayantes', 'seront', 'avions', 'sta', 'farà', 'sulle', 'ad', 'soyez', 'own', 'étant', 'tutti', 'avevamo', 'its', 'son', 'facesse', 'en', 'nostro', 'farete', 'essendo', 'those', 'tua', "aren't", 'votre', 'avete', 'aveva', "don't", 'had', 'dagli', 'aren', 'again', 'queste', 'auras', 'avevo', 'sto', 'off', 'tra', 'stando', 'li', 'avesti', 'sia', 'between', 'fai', 'stiate', 'furono', 'once', 'nella', 'hai', 'ebbero', 'tu', 'avez', 'du', 'mais', 'eurent', 'eravate', 've', 't', 'facemmo', 'étants', 'sommes', 'stavate', 'y', 'be', 'degli', 'sarebbero', 'serons', 'eût', 'mie', 'siano', 'ayants', 'dalle', 'negl', 'avranno', 'mi', 'facevamo', 'having', 'farebbero', 'hadn', 'avresti', 'under', 'quante', 'fossimo', "she's", 'stanno', 'dagl', 'her', 'as', 'était', 'avec', 'until', 'ai', 'same', 'siate', 'been', 'avons', 'fummo', 'sera', 'eravamo', 'are', 'soyons', "didn't", 'con', 'sarei', 'dai', 'o', 'after', 'an', 'qu', 'ton', 'why', 'most', 'm', 'eûtes', 'fûmes', 'needn', 'of', 'dello', 'more', 'there', 'le', 'aveste', 'stessi', 'abbiano', 'starebbero', 'facesti', 'him', 'll', 'aurait', 'e', 'êtes', 'aviez', 'stettero', 'me', 'facendo', 'la', 'della', 'qui', 'vostro', 'fareste', 'étante', 'sono', 'dallo', 'agli', 'fosse', 'aient', 'erano', 'staranno', "needn't", 'few', 'dalla', 'tuoi', 'vostra', 'sarete', 'stavano', 'here', 'seraient', 'à', 'ayante', 'aurions', 'eut', 'stette', 'a', 'at', 'nel', 'te', "that'll", 'fût', 'avevi', 'just', 'who', 'toi', 'nell', 'than', 'ne', 'questa', 'sarò', 'eue', 'dov', 'haven', 'avuto', 'vostri', 'seriez', 'coi', 'themselves', 'aurez', 'or', 'abbiamo', 'eûmes', "haven't", "shouldn't", 'sont', 'fosti', 'each', 'eus', 'saremmo', 'not', 'auraient', 'doesn', 'au', 'about', 'no', "weren't", 'aurons', 'da', 'herself', "couldn't", 'the', 'mes', 'est', 'stareste', 'both', 'quanta', 'de', 'seras', 'ho', 'what', 'stia', 'weren', 'she', 'avremmo', 'les', 'avrà', 'siete', 'faremo', 'any', 'yourself', 'avais', 'out', 'sullo', 'des', 'si', 'étées', 'fussent', 'eussiez', 'so', 'che', 'abbia', 'que', 'lo', 'nor', 'abbiate', 'étée', 'farei', 'suoi', 'quella', 'has', 'only', 'contro', 'ours', 'myself', 'faccia', 'does', 'stessero', 'avremo', 'in', 'mia', 'avrebbe', 'while', 'which', 'wasn', "mightn't", 'saremo', 'ci', "doesn't", 'su', 'nous', 'fûtes', 'aie', 'suo', 'l', 'but', 'dans', 'fus', 'del', 'fusses', 'shan', 'un', 'j', 'other', 'avuti', 'avrete', 'col', 'avessimo', 'notre', 'gli', 'soit', 'dall', 'mightn', 'ain', 'it', 'did', 'faranno', 'se', 'facessero', 'et', 'non', 'starà', 'do', 'eri', 'am', 'into', 'sui', 'mustn', "mustn't", 'fusse', 'uno', 'sa', 'di', "you've", 'été', 'furent', 'eues', 'nostri', 'he', 'delle', 'è', 'for', 'auriez', 'anche', 'farebbe', 'itself', 'faremmo', 'vous', 'aura', 'étions', 'soient', 'if', 'chi', 'facessimo', 'miei', 'hanno', 'allo', 'sull', 'nelle', 'perché', 'facevo', 'sulla', 'tue', 'facessi', 'such', 'theirs', 'and', 'serez', 'eusses', 'facciano', 'sul', 'facciate', 'have', 'hasn', 'fu', 'should', 'was', 'sua', 'avrebbero', 'that', 'étais', 'nello', 'cui', 'stessimo', 'alle', 'dove', 'below', 'over', "should've", 'is', 'aux', 'serai', 'staremmo', 'pas', 'quanto', 'avevano', 'vos', 'ait', 'avute', 'al', 'avrai', 'per', 'faceva', 'faccio', 'noi', 'during', 'yours', 'étés', 'foste', 'siamo', 'against', 'faceste', 'auront', 'hers', 'fanno', 'io', 'then', 'staresti', 'fussions', "you'll", 'une', 'being', 'tes', 'this', "you'd", 'quanti', 'when', 'più', 'starai', 'through', 'didn', 'avaient', 'eu', 'steste', 'where', 'come', 'them', 'aies', 'couldn', "you're", 'faresti', 'i', 'facevate', "shan't", 'feci', 'with', 'questo', 'stai', 'saresti', 'stesse', 'my', 'era', 'fece', 'shouldn', 'avrò', 'fui', 'starei', 'can', 'starebbe', "isn't", 'leur', 'ta', 'fossero', 'sei', 'they', 'ebbi', 'stiano', "wasn't", 'avreste', 'ce', 'ayez', 'serais', 'yourselves', 'avesse', 'ed', 'sarà', "hadn't", 'je', 'eux', 'don', 'questi', 'stavi', 'stesti', 're', 'himself', 'es', 'stava', 'saranno', 'avevate', 'by', 'fossi', 'farò', 'their', 'all', 'fecero', 'stavo', 'nei', 'sarai', 'sue', 'because', 'elle', 'fut', 'degl', 'down', 'suis', 'avessero', 'dal', 'how', 'will', 'were', 'étaient', 'avuta', 'stavamo', 'ayant', 'eussions', 'voi', 'negli', "it's", 'wouldn', 'ils', 'n', 'too', 'serait', 'serions', 'ebbe', 'some', 'stiamo', 'staremo', 'stemmo', 'your', 'dei', 'ha', 'avendo', 'lui', 'starete', 'ont', 'dell', 'avessi', 'ces', 'mio', 'ourselves', 'very', 'tuo', 'quello', 'from', 'il', "wouldn't", 'sur', 'sois', 'fussiez', 'now', 'won', 'further', 'eusse', 'loro', 'quelli', 'we', 'c', 'these', 'ou', 'ayons', 'our', 'quale', 'sarebbe', 'agl', 'to', 'above', 'facevi', 'doing', 'alla', 's', 'pour', 'd', 'isn', 'par', 'ero', 'avemmo', 'sareste', 'facciamo', 'starò', 'before', 'his', 'ses', 'aurai', 'una', 'avrei', 'farai', 'nostra', 'quelle', 'sugli', 'facevano', 'eussent', 'aurais', 'whom', "hasn't", 'nostre', 'même', "won't", 'mon', 'vostre', 'moi', 'ma', 'étiez', 'étantes']
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
import streamlit as st
|
6 |
-
import scattertext as stx
|
7 |
-
from scattertext import CorpusFromPandas
|
8 |
-
from scattertext.WhitespaceNLP import whitespace_nlp
|
9 |
-
import pandas as pd
|
10 |
-
import nltk
|
11 |
-
from nltk.tokenize import word_tokenize
|
12 |
-
#from nltk.corpus import stopwords
|
13 |
-
import plotly.express as px
|
14 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
15 |
-
import matplotlib.pyplot as plt
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
################
|
20 |
-
#download function
|
21 |
-
import requests
|
22 |
-
import time
|
23 |
-
import pandas as pd
|
24 |
-
import urllib.parse
|
25 |
-
import datetime
|
26 |
-
|
27 |
-
from io import StringIO
|
28 |
-
|
29 |
-
|
30 |
-
def download_steam_api(app_id):
|
31 |
-
# Imposta il cursore iniziale
|
32 |
-
cursor = '*'
|
33 |
-
|
34 |
-
|
35 |
-
# Lista per raccogliere tutte le recensioni
|
36 |
-
reviews_data = []
|
37 |
-
|
38 |
-
|
39 |
-
while True:
|
40 |
-
# Parametri per la richiesta API
|
41 |
-
params = { 'filter': 'recent','language': 'all','review_type': 'all','purchase_type': 'all','num_per_page': 100,'cursor': cursor,'json': 1}
|
42 |
-
|
43 |
-
# Genera la query string
|
44 |
-
query_string = urllib.parse.urlencode(params)
|
45 |
-
request_url = f'https://store.steampowered.com/appreviews/{app_id}?{query_string}'
|
46 |
-
|
47 |
-
print(f"Effettuo richiesta a: {request_url}")
|
48 |
-
st.write(f"Effettuo richiesta a: {request_url}")
|
49 |
-
|
50 |
-
# Effettua la richiesta
|
51 |
-
response = requests.get(request_url)
|
52 |
-
|
53 |
-
# Se la richiesta non va a buon fine, interrompi
|
54 |
-
if response.status_code != 200:
|
55 |
-
print("Errore nella richiesta:", response.status_code)
|
56 |
-
break
|
57 |
-
|
58 |
-
# Converte la risposta in JSON
|
59 |
-
data = response.json()
|
60 |
-
|
61 |
-
# Se non ci sono recensioni, esce dal ciclo
|
62 |
-
if not data.get('reviews') or len(data['reviews']) == 0:
|
63 |
-
print("Nessuna recensione trovata, fine ciclo.")
|
64 |
-
break
|
65 |
-
|
66 |
-
|
67 |
-
# Aggiorna il cursore per la prossima pagina
|
68 |
-
cursor = data.get('cursor')
|
69 |
-
|
70 |
-
|
71 |
-
# Processa ogni recensione
|
72 |
-
for review in data['reviews']:
|
73 |
-
# Conversione del timestamp in data formattata
|
74 |
-
timestamp = review.get('timestamp_created')
|
75 |
-
review_date = datetime.datetime.fromtimestamp(timestamp).strftime('%Y.%m.%d %H:%M') if timestamp else ''
|
76 |
-
|
77 |
-
|
78 |
-
# Costruisce il dizionario dei dati della recensione
|
79 |
-
reviews_data.append({
|
80 |
-
'Review ID': review.get('recommendationid'),
|
81 |
-
'Language': review.get('language'),
|
82 |
-
'Date Posted': review_date, # già convertito in formato "YYYY.MM.DD HH:MM" precedentemente
|
83 |
-
'Timestamp Updated': datetime.datetime.fromtimestamp(review.get('timestamp_updated')).strftime("%Y-%m-%d %H:%M:%S") if review.get('timestamp_updated') else '',
|
84 |
-
'Recommended': '1' if review.get('voted_up') else '0',
|
85 |
-
'Steam Purchase': '1' if review.get('steam_purchase') else '0',
|
86 |
-
'Weighted Vote Score': review.get('weighted_vote_score'),
|
87 |
-
'Votes Up': review.get('votes_up'),
|
88 |
-
'Votes Funny': review.get('votes_funny'),
|
89 |
-
'Comment Count': review.get('comment_count'),
|
90 |
-
'Received For Free': '1' if review.get('received_for_free') else '0',
|
91 |
-
'Written During Early Access': '1' if review.get('written_during_early_access') else '0',
|
92 |
-
'Primarily Steam Deck': '1' if review.get('primarily_steam_deck') else '0',
|
93 |
-
'Review Text': review.get('review'),
|
94 |
-
# Informazioni sull'autore
|
95 |
-
'Author SteamID': review.get('author', {}).get('steamid'),
|
96 |
-
'Num Games Owned': review.get('author', {}).get('num_games_owned'),
|
97 |
-
'Num Reviews': review.get('author', {}).get('num_reviews'),
|
98 |
-
'Playtime Forever': review.get('author', {}).get('playtime_forever'),
|
99 |
-
'Playtime Last Two Weeks': review.get('author', {}).get('playtime_last_two_weeks'),
|
100 |
-
'Playtime At Review': review.get('author', {}).get('playtime_at_review'),
|
101 |
-
'Last Played': datetime.datetime.fromtimestamp(review.get('author', {}).get('last_played')).strftime("%Y-%m-%d %H:%M:%S") if review.get('author', {}).get('last_played') else ''
|
102 |
-
})
|
103 |
-
|
104 |
-
|
105 |
-
# (Facoltativo) Attende un attimo per non sovraccaricare l'endpoint
|
106 |
-
time.sleep(1)
|
107 |
-
|
108 |
-
|
109 |
-
# Crea un DataFrame dai dati raccolti
|
110 |
-
df_reviews = pd.DataFrame(reviews_data)
|
111 |
-
|
112 |
-
return df_reviews
|
113 |
-
|
114 |
-
|
115 |
-
# Funzione per la tokenizzazione usando nltk e rimuovere le stopwords
|
116 |
-
def clean_text(text):
|
117 |
-
# Tokenizza il testo usando nltk
|
118 |
-
tokens = word_tokenize(str(text).lower())
|
119 |
-
|
120 |
-
# Rimuovi le stopwords dal testo
|
121 |
-
filtered_tokens = [word for word in tokens if word not in all_stopwords]
|
122 |
-
|
123 |
-
return ' '.join(filtered_tokens)
|
124 |
-
|
125 |
-
############################################# Interfaccia
|
126 |
-
|
127 |
-
# Interfaccia Streamlit
|
128 |
-
st.title("Steam Review Dashboard")
|
129 |
-
|
130 |
-
# Carica o scarica le recensioni
|
131 |
-
app_id = st.text_input("Inserisci l'App ID di Steam (può impiegare alcuni minuti):", "")
|
132 |
-
|
133 |
-
if st.button("Scarica Recensioni"):
|
134 |
-
if app_id:
|
135 |
-
df = download_steam_api(app_id)
|
136 |
-
st.write("Recensioni scaricate con successo!")
|
137 |
-
#st.write(df.head()) # Mostra le prime righe per il controllo
|
138 |
-
else:
|
139 |
-
st.error("Inserisci un App ID valido.")
|
140 |
-
|
141 |
-
# Carica un file CSV
|
142 |
-
uploaded_file = st.file_uploader("Carica un file CSV", type=["csv"])
|
143 |
-
|
144 |
-
if uploaded_file is not None:
|
145 |
-
df = pd.read_csv(uploaded_file)
|
146 |
-
#st.write("Prime righe del file caricato:", df.head())
|
147 |
-
|
148 |
-
# Mostra un'opzione per scaricare il DataFrame
|
149 |
-
def download_csv(df):
|
150 |
-
csv = df.to_csv(index=False)
|
151 |
-
st.download_button(
|
152 |
-
label="Scarica il CSV",
|
153 |
-
data=csv,
|
154 |
-
file_name="steam_reviews.csv",
|
155 |
-
mime="text/csv"
|
156 |
-
)
|
157 |
-
|
158 |
-
# Pulsante per scaricare il CSV
|
159 |
-
if 'df' in locals():
|
160 |
-
download_csv(df)
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
##############à Messaggio
|
166 |
-
|
167 |
-
# Calcola il volume totale di recensioni
|
168 |
-
volume = len(df)
|
169 |
-
|
170 |
-
# Calcola il numero di recensioni raccomandate (1) e non raccomandate (0)
|
171 |
-
totpos = df['Recommended'].astype(int).sum() # Assumendo che 1 = raccomandato
|
172 |
-
totneg = volume - totpos # Il resto sono non raccomandate
|
173 |
-
|
174 |
-
# Calcola la percentuale di recensioni raccomandate e non raccomandate
|
175 |
-
percentpos = (totpos / volume) * 100
|
176 |
-
percentneg = (totneg / volume) * 100
|
177 |
-
|
178 |
-
# Trova le date minime e massime
|
179 |
-
mindate = df['Date Posted'].min()
|
180 |
-
maxdate = df['Date Posted'].max()
|
181 |
-
|
182 |
-
# Calcola il numero di recensioni per lingua
|
183 |
-
lingua_counts = df['Language'].value_counts()
|
184 |
-
primalingua = lingua_counts.index[0] if len(lingua_counts) > 0 else "N/D"
|
185 |
-
totperclingua1 = lingua_counts.iloc[0] if len(lingua_counts) > 0 else 0
|
186 |
-
secondalingua = lingua_counts.index[1] if len(lingua_counts) > 1 else "N/D"
|
187 |
-
totperclingua2 = lingua_counts.iloc[1] if len(lingua_counts) > 1 else 0
|
188 |
-
terzalingua = lingua_counts.index[2] if len(lingua_counts) > 2 else "N/D"
|
189 |
-
totperclingua3 = lingua_counts.iloc[2] if len(lingua_counts) > 2 else 0
|
190 |
-
|
191 |
-
# Format della frase
|
192 |
-
message = (f"Per il file caricato ho trovato {volume} recensioni, "
|
193 |
-
f"di cui il {percentpos:.2f}% raccomandate e il {percentneg:.2f}% non raccomandate, "
|
194 |
-
f"comprese tra {mindate} e {maxdate}, principalmente in {primalingua} ({totperclingua1}), "
|
195 |
-
f"{secondalingua} ({totperclingua2}) e {terzalingua} ({totperclingua3}).")
|
196 |
-
|
197 |
-
# Visualizza la frase
|
198 |
-
st.write(message)
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
################àà Filtro iniziale
|
203 |
-
|
204 |
-
df['Review Text'] = df['Review Text'].apply(lambda x: clean_text(x))
|
205 |
-
# Visualizza le prime righe del DataFrame
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
# Filtro per lingua (di default "english" o "Tutti" per nessun filtro)
|
210 |
-
language_filter = st.selectbox("Seleziona la lingua o tutte le lingue", ['Tutti'] + df['Language'].unique().tolist(), index=0)
|
211 |
-
if language_filter != 'Tutti':
|
212 |
-
df_filtered = df[df['Language'] == language_filter]
|
213 |
-
else:
|
214 |
-
df_filtered = df # Nessun filtro sulla lingua
|
215 |
-
|
216 |
-
#### Plot dataframe
|
217 |
-
|
218 |
-
# Ordina inizialmente per "Votes Up"
|
219 |
-
df_sorted = df_filtered.sort_values(by='Votes Up', ascending=False)
|
220 |
-
|
221 |
-
# Permetti all'utente di scegliere il criterio di ordinamento
|
222 |
-
sort_by = st.selectbox(
|
223 |
-
"Scegli la colonna per ordinare",
|
224 |
-
['Votes Up', 'Votes Funny', 'Comment Count', 'Num Games Owned'],
|
225 |
-
index=0
|
226 |
-
)
|
227 |
-
|
228 |
-
# Ordina il DataFrame in base alla scelta dell'utente
|
229 |
-
df_sorted = df_sorted.sort_values(by=sort_by, ascending=False)
|
230 |
-
|
231 |
-
# Mostra un selettore per quante righe visualizzare
|
232 |
-
num_rows = st.slider("Seleziona il numero di righe da visualizzare", min_value=5, max_value=50, value=5)
|
233 |
-
|
234 |
-
col_plot_sort = ['Review Text','Recommended','Date Posted','Language','Votes Up', 'Votes Funny', 'Comment Count', 'Num Games Owned','Last Played']
|
235 |
-
# Visualizza le prime righe del DataFrame ordinato e filtrato
|
236 |
-
st.write(f"Prime {num_rows} righe del file caricato (ordinate per {sort_by}):", df_sorted[col_plot_sort].head(num_rows))
|
237 |
-
|
238 |
-
|
239 |
-
##### **Pie Chart per la distribuzione delle recensioni (Raccomandato vs Non Raccomandato)**
|
240 |
-
st.subheader("Distribuzione delle Recensioni per Raccomandazione")
|
241 |
-
fig_pie = px.pie(df_filtered, names='Recommended', title='Distribuzione Raccomandazione delle Recensioni')
|
242 |
-
st.plotly_chart(fig_pie)
|
243 |
-
|
244 |
-
##### **Serie Temporale delle recensioni**
|
245 |
-
st.subheader("Serie Temporale delle Recensioni")
|
246 |
-
df_filtered['Date Posted'] = pd.to_datetime(df_filtered['Date Posted'], errors='coerce') # Assicurati che la colonna 'Date Posted' sia di tipo datetime
|
247 |
-
df_filtered['Date'] = df_filtered['Date Posted'].dt.date # Estrai solo la data (senza l'ora)
|
248 |
-
|
249 |
-
# Seleziona la granularità (giorno, mese, anno)
|
250 |
-
time_granularity = st.selectbox("Seleziona la granularità della serie temporale", ["Giorno", "Mese", "Anno"])
|
251 |
-
|
252 |
-
# Aggrega le recensioni in base alla granularità scelta
|
253 |
-
if time_granularity == "Giorno":
|
254 |
-
df_time_series = df_filtered.groupby('Date').size().reset_index(name='Recensioni')
|
255 |
-
elif time_granularity == "Mese":
|
256 |
-
df_filtered['Month'] = df_filtered['Date Posted'].dt.to_period('M')
|
257 |
-
df_filtered['Month'] = df_filtered['Month'].astype(str) # Converte Period in stringa
|
258 |
-
df_time_series = df_filtered.groupby('Month').size().reset_index(name='Recensioni')
|
259 |
-
else:
|
260 |
-
df_filtered['Year'] = df_filtered['Date Posted'].dt.year
|
261 |
-
df_time_series = df_filtered.groupby('Year').size().reset_index(name='Recensioni')
|
262 |
-
|
263 |
-
# Selezione per split Recommended vs Non Recommended
|
264 |
-
split_by_recommended = st.radio("Vuoi suddividere la serie temporale per Raccomandazione?", ('No', 'Sì'))
|
265 |
-
|
266 |
-
if split_by_recommended == 'Sì':
|
267 |
-
df_recommended = df_filtered[df_filtered['Recommended'] == 1]
|
268 |
-
df_not_recommended = df_filtered[df_filtered['Recommended'] == 0]
|
269 |
-
|
270 |
-
# Aggrega separatamente per "Recommended" e "Not Recommended"
|
271 |
-
if time_granularity == "Giorno":
|
272 |
-
df_recommended_ts = df_recommended.groupby('Date').size().reset_index(name='Recensioni')
|
273 |
-
df_not_recommended_ts = df_not_recommended.groupby('Date').size().reset_index(name='Recensioni')
|
274 |
-
elif time_granularity == "Mese":
|
275 |
-
df_recommended_ts = df_recommended.groupby('Month').size().reset_index(name='Recensioni')
|
276 |
-
df_not_recommended_ts = df_not_recommended.groupby('Month').size().reset_index(name='Recensioni')
|
277 |
-
else:
|
278 |
-
df_recommended_ts = df_recommended.groupby('Year').size().reset_index(name='Recensioni')
|
279 |
-
df_not_recommended_ts = df_not_recommended.groupby('Year').size().reset_index(name='Recensioni')
|
280 |
-
|
281 |
-
# Crea i grafici separati per Recommended e Not Recommended
|
282 |
-
fig_recommended = px.line(df_recommended_ts, x=df_recommended_ts.columns[0], y='Recensioni', title='Recensioni Raccomandate nel Tempo')
|
283 |
-
fig_not_recommended = px.line(df_not_recommended_ts, x=df_not_recommended_ts.columns[0], y='Recensioni', title='Recensioni Non Raccomandate nel Tempo')
|
284 |
-
|
285 |
-
st.plotly_chart(fig_recommended)
|
286 |
-
st.plotly_chart(fig_not_recommended)
|
287 |
-
else:
|
288 |
-
# Mostra la serie temporale aggregata per tutti
|
289 |
-
fig_time_series = px.line(df_time_series, x=df_time_series.columns[0], y='Recensioni', title='Numero di Recensioni nel Tempo')
|
290 |
-
st.plotly_chart(fig_time_series)
|
291 |
-
|
292 |
-
##################################################################################
|
293 |
-
|
294 |
-
|
295 |
-
# **Generazione dei barplot per le parole più frequenti**
|
296 |
-
st.subheader("Le 20 Parole più Frequenti nelle Recensioni")
|
297 |
-
|
298 |
-
# Impostazione dell'utente per decidere quante parole visualizzare
|
299 |
-
n_words = st.slider("Seleziona il numero di parole da visualizzare", min_value=5, max_value=50, value=20)
|
300 |
-
|
301 |
-
def counter_words(df_counter,n_words):
|
302 |
-
|
303 |
-
df_counter['Review Text'] = df_counter['Review Text'].astype(str)
|
304 |
-
|
305 |
-
# Filtro delle recensioni raccomandate (1) e non raccomandate (0)
|
306 |
-
df_counter['Recommended'] = df_counter['Recommended'].astype(str) # Converte in stringa
|
307 |
-
df_recommended = df_counter[df_counter['Recommended'] == '1']
|
308 |
-
df_not_recommended = df_counter[df_counter['Recommended'] == '0']
|
309 |
-
|
310 |
-
|
311 |
-
# Funzione per estrarre le parole più frequenti usando TfidfVectorizer
|
312 |
-
def get_most_common_words(text_data, n):
|
313 |
-
# Usa TfidfVectorizer per tokenizzare e contare le parole
|
314 |
-
#vectorizer = TfidfVectorizer(stop_words='english', max_features=n)
|
315 |
-
vectorizer = TfidfVectorizer(stop_words='english', max_features=n)
|
316 |
-
X = vectorizer.fit_transform(text_data)
|
317 |
-
word_freq = dict(zip(vectorizer.get_feature_names_out(), X.toarray().sum(axis=0)))
|
318 |
-
return word_freq
|
319 |
-
|
320 |
-
# Estrai il testo delle recensioni
|
321 |
-
text_recommended = df_recommended['Review Text'].dropna()
|
322 |
-
text_not_recommended = df_not_recommended['Review Text'].dropna()
|
323 |
-
|
324 |
-
print(text_recommended)
|
325 |
-
print(text_not_recommended)
|
326 |
-
|
327 |
-
# Ottieni le parole più frequenti
|
328 |
-
recommended_word_freq = get_most_common_words(text_recommended, n_words)
|
329 |
-
not_recommended_word_freq = get_most_common_words(text_not_recommended, n_words)
|
330 |
-
|
331 |
-
# Ordina le parole in ordine decrescente di frequenza
|
332 |
-
recommended_word_freq = dict(sorted(recommended_word_freq.items(), key=lambda item: item[1], reverse=True))
|
333 |
-
not_recommended_word_freq = dict(sorted(not_recommended_word_freq.items(), key=lambda item: item[1], reverse=True))
|
334 |
-
|
335 |
-
return recommended_word_freq,not_recommended_word_freq
|
336 |
-
|
337 |
-
recommended_word_freq,not_recommended_word_freq = counter_words(df_filtered,n_words)
|
338 |
-
|
339 |
-
# Crea i plot delle parole più frequenti
|
340 |
-
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
|
341 |
-
|
342 |
-
# Parole più frequenti per recensioni raccomandate (1)
|
343 |
-
ax = axes[0]
|
344 |
-
ax.bar(recommended_word_freq.keys(), recommended_word_freq.values())
|
345 |
-
ax.set_title("Parole più frequenti (Raccomandate)")
|
346 |
-
ax.set_xticklabels(recommended_word_freq.keys(), rotation=90, ha='center') # Etichette verticali
|
347 |
-
|
348 |
-
# Parole più frequenti per recensioni non raccomandate (0)
|
349 |
-
ax = axes[1]
|
350 |
-
ax.bar(not_recommended_word_freq.keys(), not_recommended_word_freq.values())
|
351 |
-
ax.set_title("Parole più frequenti (Non Raccomandate)")
|
352 |
-
ax.set_xticklabels(not_recommended_word_freq.keys(), rotation=90, ha='center') # Etichette verticali
|
353 |
-
|
354 |
-
# Mostra il grafico
|
355 |
-
st.pyplot(fig)
|
356 |
-
|
357 |
-
|
358 |
-
##################################################################################
|
359 |
-
|
360 |
-
# **Generazione di scattertext**
|
361 |
-
st.subheader("Analisi dei Termini più Frequente con Scattertext")
|
362 |
-
st.write('Se dovesse dare errore prova a selezionare una lingua')
|
363 |
-
|
364 |
-
def scatter_text(df_scat):
|
365 |
-
|
366 |
-
# Converte 'Recommended' in stringhe per garantire la compatibilità con scattertext
|
367 |
-
df_scat['Recommended'] = df_scat['Recommended'].astype(str) # Converte in stringa
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
df_scat = df_scat[df_scat['Recommended'].isin(['0', '1'])]
|
372 |
-
|
373 |
-
df_scat['Review Text'] = df_scat['Review Text'].fillna('').astype(str)
|
374 |
-
df_scat = df_scat.dropna(subset=['Review Text', 'Recommended'])
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
# Crea un Corpus usando scattertext con la funzione custom di tokenizzazione
|
379 |
-
corpus = CorpusFromPandas(df_scat, category_col='Recommended', text_col='Review Text',
|
380 |
-
nlp=whitespace_nlp).build()
|
381 |
-
|
382 |
-
# Usa scattertext per generare l'explorer
|
383 |
-
html = stx.produce_scattertext_explorer(
|
384 |
-
corpus,
|
385 |
-
category='1', # Categoria positiva (se '1' è "Recommended")
|
386 |
-
category_name='Recensioni Raccomandate', # Nome per la categoria positiva
|
387 |
-
not_category_name='Recensioni Non Raccomandate', # Nome per la categoria negativa
|
388 |
-
minimum_term_frequency=5, # Frequenza minima per i termini
|
389 |
-
width_in_pixels=700, # Larghezza del grafico in pixel
|
390 |
-
metadata=df_scat['Review Text'] # Metadati per il grafico
|
391 |
-
)
|
392 |
-
|
393 |
-
|
394 |
-
return html
|
395 |
-
|
396 |
-
html = scatter_text(df_filtered)
|
397 |
-
# Mostra il grafico HTML generato da scattertext
|
398 |
-
st.components.v1.html(html, height=800)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|