-
Notifications
You must be signed in to change notification settings - Fork 0
/
text_processing.py
272 lines (142 loc) · 5.99 KB
/
text_processing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
## Librerías
# Procesamiento de datos
import numpy as np
import pandas as pd
# Herramientas de gramática
import language_tool_python
import contractions
import re
# Procesamiento de lenguaje natural
import nltk
from textblob import TextBlob, Word
from textblob.sentiments import PatternAnalyzer, NaiveBayesAnalyzer
# Visualizaciones
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
## Cargo el dataset
df = pd.read_csv("text_data.csv")
## Paso 1: Procesamiento de los datos
def check_mistakes(text, tool = language_tool_python.LanguageTool('en-GB')): # Busco y corrijo los errores de un solo texto
# Limpieza de formato
pattern = r"[^\w\.',]"
text = re.sub(pattern, " ", text)
text = re.sub(f"[ ]+", " ", text)
# Errores ortográficos y tipográficos
spelling_mistakes = len(tool.check(text))
text = tool.correct(text)
# Deshacer contracciones
contract = text.count("'")
correct_text = contractions.fix(text)
return spelling_mistakes, contract, correct_text
def check_data(df): # Busco y corrijo los errores de todos los textos del DataFrame
# Inicializo las listas
spelling_mistakes_list = list()
contract_list = list()
correct_text_list = list()
# Inica el servidor
tool = language_tool_python.LanguageTool('en-GB') # Servidor local
# Analizo los textos
for i in range(len(df)):
text = df["full_text"][i]
spelling_mistakes, contract, correct_text = check_mistakes(text, tool)
spelling_mistakes_list.append(spelling_mistakes)
contract_list.append(contract)
correct_text_list.append(correct_text)
# Cierra el servidor
tool.close()
# Añado los valores al DataFrame
df["correct_text"] = np.array(correct_text_list)
df["spelling_mistakes"] = np.array(spelling_mistakes_list)
df["contractions"] = np.array(contract_list)
return df
# Ejecuto el procesamiento de los datos del dataframe
correct_df = check_data(df)
correct_df.to_csv("corrected_text.csv", index = False)
## Paso 2: Procesamiento del lenguaje natural (NLP)
def get_metrics(text): # Obtengo las métricas de un solo texto
# Numero de palabras por oracion
sentences = len(nltk.sent_tokenize(text))
words = len(nltk.word_tokenize(text))
words_per_sent = words / sentences
# Riqueza del lenguaje
unique_words = len(set(nltk.word_tokenize(text)))
richness = unique_words / words
# Numero de palabras que aportan información
stopwords = nltk.corpus.stopwords.words("english")
useful_words = list()
# Elimino los signos de puntuación para analizar el texto
pattern = r"[^\w\d\s]"
clean_text = re.sub(pattern, " ", text)
clean_text = re.sub(f"[ ]+", " ", clean_text)
for word in nltk.word_tokenize(clean_text):
if word.casefold() not in stopwords :
useful_words.append(word)
informative = len(useful_words) / words
# Análisis sintáxico / morfológico
verb = ["VB", "VBD", "VBG", "VBN", "VBP", "VBZ"]
verb_list = list()
adjective = ["JJ", "JJR", "JJS"]
adjective_list = list()
adverb = ["RB", "RBR", "RBS"]
adverb_list = list()
blob = TextBlob(text)
for word in blob.tags:
if word[1] in verb:
v = Word(word[0]).lemmatize("v")
verb_list.append(v)
elif word[1] in adjective:
adjective_list.append(word[0])
elif word[1] in adverb:
adverb_list.append(word[0])
# Tipos de palabras utilizadas
unique_verbs = len(set(verb_list))
unique_adjectives = len(set(adjective_list))
unique_adverbs = len(set(adverb_list))
# Análisis del sentimiento del texto
blob = TextBlob(text, analyzer = PatternAnalyzer())
polarity = blob.sentiment[0]
subjectivity = blob.sentiment[1]
# Análisis del sentimiento del texto
#blob = TextBlob(text, analyzer = NaiveBayesAnalyzer())
#positive = blob.sentiment[1]
#negative = blob.sentiment[2]
return words_per_sent, richness, informative, unique_verbs, unique_adjectives, unique_adverbs, polarity, subjectivity
def get_metrics_data(df): # Obtengo las métricas de todos los textos del DataFrame
# Inicializo las listas
words_per_sent_list = list()
richness_list = list()
informative_list = list()
unique_verbs_list = list()
unique_adjectives_list = list()
unique_adverbs_list = list()
polarity_list = list()
subjectivity_list = list()
spelling_mistakes_list = list()
contract_list = list()
correct_text_list = list()
# Analizo los textos
for i in range(len(df)):
text = df["correct_text"][i]
words_per_sent, richness, informative, unique_verbs, unique_adjectives, unique_adverbs, polarity, subjectivity = get_metrics(text)
words_per_sent_list.append(words_per_sent)
richness_list.append(richness)
informative_list.append(informative)
unique_verbs_list.append(unique_verbs)
unique_adjectives_list.append(unique_adjectives)
unique_adverbs_list.append(unique_adverbs)
polarity_list.append(polarity)
subjectivity_list.append(subjectivity)
# Añado los valores al DataFrame
df["words_per_sent"] = np.array(words_per_sent_list)
df["richness"] = np.array(richness_list)
df["informative"] = np.array(informative_list)
df["unique_verbs"] = np.array(unique_verbs_list)
df["unique_adjectives"] = np.array(unique_adjectives_list)
df["unique_adverbs"] = np.array(unique_adverbs_list)
df["polarity"] = np.array(polarity_list)
df["subjectivity"] = np.array(subjectivity_list)
return df
# Ejecuto el procesamiento de los datos del dataframe
scored_df = get_metrics_data(correct_df)
scored_df.to_csv("scored_text.csv", index = False)