-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclust_txt_xxxs.py
2103 lines (1805 loc) · 82.1 KB
/
clust_txt_xxxs.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
CLUST -TXT XXS AZURE
"""
import sys
import logging
import time
import datetime
import os
import re
from random import randint
import math
import collections
# basic
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# nltk
# import nltk
# from nltk.corpus import stopwords
# from nltk import word_tokenize, sent_tokenize
# spacy
import spacy
import en_core_web_sm
# gensim
from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedLineDocument
from gensim.test.test_doc2vec import ConcatenatedDoc2Vec
import multiprocessing
# sklearn
from sklearn.utils import shuffle
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# clustering
from pylab import plot, show
from sklearn.cluster import KMeans
from sklearn import metrics
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.metrics import pairwise_distances
from sklearn.metrics import silhouette_score
from scipy.cluster.vq import kmeans, vq
# %% set up logging and time management module
"""
###################################################################
TIME AND LOG MANAGEMENT
###################################################################
"""
def take_time(start_time=time.time(), end_time=time.time(), process='Unknown'):
elapsed_time = end_time - start_time
total_time = str(datetime.timedelta(seconds=elapsed_time))
# df_time.append({ 'process':process, 'start_time':start_time, 'end_time':end_time, 'total_time':total_time}, ignore_index=True)
print("Process %", process)
print("START %s" % start_time)
print("END %s" % end_time)
print("TOTAL %s" % total_time)
return {'process': process, 'total_time': total_time}
# %% user defined parameters
"""
###################################################################
SET USER DEFINED PARAMETERS
###################################################################
"""
def FileForPrinting(path):
"""
with open(path, "w+", encoding='utf-8') as text_file:
print(f'{str(len(sys.argv))} /n', file=text_file)
for i_index in range(0, len(sys.argv) - 1):
print(f'{str(sys.argv[i_index]} /n', file=text_file)
"""
with open(path, "w+", encoding='utf-8') as text_file:
print(f'{str(11111)} /n', file=text_file)
for i_index in range(0, len(sys.argv) - 1):
print(f'{str(sys.argv[i_index]} /n', file=text_file)
def SetParameters(df_time):
print(__doc__)
print("SCRIPT START")
arg_names = ['file_path', 'experiment', 'experiment_ref', 'parameter_type', 'model', 'dim_reduction', 'pipeline']
FileForPrinting(os.path.join(os.getcwd() + '/ConsoleArgs.txt'))
args = dict(zip(arg_names, sys.argv))
default = False
# print("Python File:", args['file_path'])
if (len(args) <= 1 or len(args) < len(arg_names)):
sys.argv.append(20) # experiment number
sys.argv.append(0) # experiment_ref
sys.argv.append(0) # parameter_type
sys.argv.append(2) # model
sys.argv.append(1) # dim_reduction
sys.argv.append("5") # pipeline flow
default = True
args = dict(zip(arg_names, sys.argv)) # se guardan en un dictionary
else:
print("Reading Arguments")
for i, key_value in enumerate(args.items()):
value = key_value[1]
if (key_value[1] == "-1" and i > 0):
key = key_value[0]
args[key] = 0
print(key)
print(value)
# current working directory
if (args['file_path'] != None):
file_path = args['file_path']
base_path = os.path.join(os.path.dirname(args['file_path']) + '/')
else:
base_path = os.path.join(os.getcwd() + '/') # gets current working directory
docs_name = ['AM.xlsx', 'english_tickets_1.xlsx', 'english_tickets_2.xlsx', 'spanish_tickets.xlsx',
'descripcion.xlsx', 'alstrom_descriptions.xlsx', 'historical_incidents.xlsx']
doc = ""
# experiment_ref=int(args['experiment_ref'])
if 'doc' in args:
doc_name = docs_name[args['doc']]
else:
if not default:
doc_name = 'EXPERIMENT_' + str(args['experiment'])
doc = args['experiment']
else:
doc_name = docs_name[0]
print(doc_name)
"""
model to choose
0- faster
1- mix
2- paper
3- paper-tuned
"""
model = int(args['model']) # 0-new , 1-pretrained, 2- own_pretrained_model
# %% adjust parameters
"""
*****************
change to default arguments if needed
****************
"""
# en default model es 0
if (model == 0 or (model != 1 and model != 2) or model == -1):
pretrained_emb = False
own_model = False
train = True
model = "new"
else:
if (model == 1):
pretrained_emb = True
own_model = False
train = False
model = 'pretrained_emb'
else:
if (model == 2):
pretrained_emb = False
own_model = True
train = False
model = 'own_model'
# %% print in console and set EXPERIMENT
# print("Parameters sent DATAFRAME")
# print("base_path ", base_path)
# paper trained default
print("Parameters sent")
print("experiment: ", args['experiment'])
print("experiment_ref: ", args['experiment_ref'])
print("parameter_type: ", int(args['parameter_type'])) # faster 0, middle 1, accuracy- 2, acccuracy-tuned 3
print("dimensionality reduction ", int(args['dim_reduction'])) # 1-pca , 2-tsne
print("pipeline: ", args['pipeline'])
print("model: ", model)
experiment_stage = "EXPERIMENT_"
experiment_name = experiment_stage + str(args['experiment'])
print('Experiment name: ' + experiment_name)
end_time = time.time()
df_time = df_time.append(take_time(start_time, end_time, 'SET PARAMETERS'), ignore_index=True)
print(df_time)
# %% storage
"""
###################################################################
STORAGE
###################################################################
"""
"""
****************************
MAIN FOLDERS
****************************
"""
if not os.path.exists(os.path.join(base_path + "Datasets")):
os.makedirs(os.path.join(base_path + "Datasets"))
if not os.path.exists(os.path.join(base_path + "Models")):
os.makedirs(os.path.join(base_path + "Models"))
if not os.path.exists(os.path.join(base_path + '/' + "Metadata")):
os.makedirs(os.path.join(base_path + '/' + "Metadata"))
if not os.path.exists(os.path.join(base_path + "Results")):
os.makedirs(os.path.join(base_path + "Results"))
if not os.path.exists(os.path.join(base_path + '/' + "Clustering")):
os.makedirs(os.path.join(base_path + '/' + "Clustering"))
if not os.path.exists(os.path.join(base_path + '/ ' + "Dim Reduction")):
os.makedirs(os.path.join(base_path + '/ ' + "Dim Reduction"))
"""
*************
EXPERIMENT SPECIFIC PATHS
*************
"""
# in results folder
if not os.path.exists(os.path.join(base_path + "Datasets" + '/' + "EXPERIMENT_" + str(args['experiment']))):
os.makedirs(os.path.join(base_path + "Datasets" + '/' + "EXPERIMENT_" + str(args['experiment'])))
if not os.path.exists(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name)):
os.makedirs(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name))
if not os.path.exists(os.path.join(base_path + '/' + "Metadata" + '/' + "METADATA_" + experiment_name)):
os.makedirs(os.path.join(base_path + '/' + "Metadata" + '/' + "METADATA_" + experiment_name))
if not os.path.exists(os.path.join(base_path + '/' + "Clustering" + '/' + "CLUSTERING_" + experiment_name)):
os.makedirs(os.path.join(base_path + '/' + "Clustering" + '/' + "CLUSTERING_" + experiment_name))
if not os.path.exists(os.path.join(base_path + '/ ' + "Dim Reduction" + '/' + "DIM_REDUCTION_" + experiment_name)):
os.makedirs(os.path.join(base_path + '/ ' + "Dim Reduction" + '/' + "DIM_REDUCTION_" + experiment_name))
if not os.path.exists(os.path.join(base_path + '/ ' + "Results" + '/' + experiment_name)):
os.makedirs(os.path.join(base_path + '/ ' + "Results" + '/' + experiment_name))
"""
*************
SAVE IN RESULTS_EXPERIMENT FILES
*************
"""
if (default):
file_path = os.path.join(base_path + "Datasets" + '/' + doc_name)
else:
file_path = os.path.join(base_path + "Datasets" + '/' + doc_name + '.xlsx')
"""
#global path
model_file_path = os.path.join(base_path + "Models" + '/' + "Model_" + str(experiment_name))
model_doctag_file_path = os.path.join(base_path + "Models" + '/' + "model_doctag")
#results
training_data_path = os.path.join(base_path + "Results" + '/' + "EXPERIMENT_" + str(args['experiment']) + '/' + "training_data.csv")
test_data_path = os.path.join(base_path + "Results" + '/' + "EXPERIMENT_" + str(args['experiment']) + '/' + "test_data.txt")
similar_path = os.path.join(base_path + "Results" + '/' + "EXPERIMENT_" + str(args['experiment']) + '/' + "similar_random.csv")
#metadata
parameters_file_path = os.path.join(base_path + '/' + "Metadata" + '/' + "METADATA_" + experiment_name + '/' + experiment_name + "_parameters")
#clustering
clustering_pca_file_path = os.path.join(base_path + '/' + "Clustering" + '/' + "CLUSTERING_" + experiment_name + '/' + "clustering_PCA.txt")
clustering_tsne_file_path = os.path.join(base_path + '/' + "Clustering" + '/' + "CLUSTERING_" + experiment_name + '/' + "clustering_TSNE.txt")
"""
resp = {
"doc": doc,
"doc_name": doc_name,
"dim_reduction": int(args['dim_reduction']),
"pretrained_emb": pretrained_emb,
"own_model": own_model,
"train": train,
"model": model,
"base_path": base_path,
"experiment_name": experiment_name,
"args": args,
"file_path": file_path,
"df_time": df_time
}
return resp
# %% MAIN
"""
###################################################################
PREPROCESSING
###################################################################
"""
"""
Preprocessing techniques:
- Tokenization
- Stop Word Removal
- Lower Case and Punctuation or Number removal
"""
def Preprocessing(df_time, base_path, experiment_name, args, file_path, pipe_flow):
# loading model
nlp = spacy.load('en')
# fetch data
start_time = time.time() # contamos el tiempo
file = FetchData(file_path) # metodo para sacar los datos del archivo
end_time = time.time() # terminamos el conteo del tiempo
df_time = df_time.append(take_time(start_time, end_time, 'FILE READING 1'), ignore_index=True)
print('File shape ', file.shape)
vocab_size = file.shape[0] - 1
file = shuffle(file)
train = False
start_time = time.time()
"""
Se va a seguir el flujo empleado por lo que el usuario escoge
Default es mi preferencia
"""
for pipe in pipe_flow:
if pipe != ' ':
if pipe == "1":
print('Pipeline One')
pipeline = CleaningCorpora(nlp, file, vocab_size) #stop words, -
if pipe == "2":
print('Pipeline Two')
pipeline = CleaningCorporaTwo(nlp, file, vocab_size)
if pipe == "3":
print('Pipeline Three')
pipeline = CleaningCorporaThree(nlp, file, vocab_size) #greetings y farewells
if pipe == "4":
print('Pipeline Four')
pipeline = CleaningCorporaFour(nlp, file, vocab_size)
if pipe == "5":
print('Pipeline Five')
pipeline = CleaningCorporaThree(nlp, file, vocab_size, base_path)
pipeline = CleaningCorpora(nlp, pd.DataFrame({'col':pipeline['corpus_preprocessed']}), vocab_size)
pipeline = CleaningCorporaFour(nlp, pd.DataFrame({'col':pipeline['corpus_preprocessed']}), vocab_size)
#preprocessing = CleaningCorpora(nlp, file, vocab_size) # stopwords and NER
#pipeplines
#pipelineOne = CleaningCorpora(nlp, file, vocab_size) #stop words, -
#pipelineTwo = CleaningCorporaTwo(nlp, file, vocab_size)
#pipelineThree = CleaningCorporaThree(nlp, file, vocab_size) #greetings y farewells
#pipelineFour = CleaningCorporaFour(nlp, file, vocab_size)
# corpus_preprocessed corpus_raw entities
print("Preprocessing Finished")
# split data
# df_file['training_data'] = df_file[:math.floor(vocab_size * .8)]
# df_file['test_data'] = df_file[math.ceil(vocab_size * .2):]
docs_used = pd.DataFrame({'preprocessed_sentence': pipeline['corpus_preprocessed']})
model = pipeline['corpus_preprocessed']
model = pd.DataFrame({'preprocessed_sentence': model[:int(vocab_size * 0.8)]})
train = pipeline['corpus_preprocessed']
train = pd.DataFrame({'preprocessed_sentence': train[int(vocab_size * 0.8):]})
docs_original = pd.DataFrame({'sentences': pipeline['corpus_raw']})
docs_xxs = pd.DataFrame({'entities': pipeline['entities']})
docs_used.to_csv(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name + '/' + "dataset.txt"),
sep='\t', encoding='utf-8', index=False, header=None)
model.to_csv(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name + '/' + "modelSample.txt"),
sep='\t', encoding='utf-8', index=False, header=None)
train.to_csv(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name + '/' + "trainSample.txt"),
sep='\t', encoding='utf-8', index=False, header=None)
docs_xxs.to_csv(os.path.join(base_path + "Datasets" + '/' + "PREPROCESS_" + experiment_name + '/' + "sentences_xxs.txt"),
encoding='utf-8', index=False, header=None)
"""
docs_original.to_csv(os.path.join(base_path + "Results" + '/' + experiment_name + '/' + "original_dataset.csv"),
encoding='utf-8', index=False, header=None)
"""
end_time = time.time()
df_time = df_time.append(take_time(start_time, end_time, 'PREPROCESSING '), ignore_index=True)
end_time = time.time()
df_time = df_time.append(take_time(start_time, end_time, 'NER + StopWords'), ignore_index=True)
# regresamos el vocab_size, training y resp
data = {
"vocab_size": vocab_size,
"train": train,
"pipeline": pipeline,
"df_time": df_time
}
return data
def FetchData(file_path):
print("Fetching data from file in ", file_path)
df_file = pd.read_excel(file_path, usecols="A")
return df_file
def FetchInfo(file_path):
print("Fetching data from file in ", file_path)
txt_file = open(file_path, 'r')
return txt_file
#vamos a eliminar los greetings
def RemoveGreetings(sentence, greetings):
try:
#checamos si tiene formato de espacios
if '\n' in sentence:
#hacemos el split
greeting = sentence.split('\n')
for i in range(len(greeting) - 1):
words = greeting[i].split(' ')
if words[0].lower() in greetings:
#tenemos en el dictionary la primera palabra
#es un greeting
#checamos si tiene una coma
if ',' in greeting[i]:
#eliminamos desde el greeting hasta la coma
index = greeting[i].find(',')
#sentence = sentence.replace('\n', ' ')
substring = greeting[i]
#print(substring[0:index+1])
sentence = sentence.replace(substring[0:index+1], '')
sentence = RemoveWhiteSpaces(sentence)
else:
#no tiene coma, solo eliminamos el greeting encontrado
#checamos el length del greeting
if len(greeting[i]) >= len(sentence) / 4:
#eliminamos solo el greeting
#sentence = sentence.replace('\n', ' ')
word = greeting[i].split(' ')
index = greeting[i].lower().find(word[0].lower())
substring = greeting[i]
#sentence = sentence.replace(word[0], '')
sentence = sentence.replace(substring[index:len(word[0])], '')
sentence = RemoveWhiteSpaces(sentence)
#print(word[0])
else:
#se elimina todo
#sentence = sentence.replace('\n', ' ')
sentence = sentence.replace(greeting[i], '')
sentence = RemoveWhiteSpaces(sentence)
#print(greeting[0])
#encontró el greeting, nos salimos del ciclo
break
else:
#not in greetings
#checamos si es parte del greeting
for key, value in greetings.items():
if words[0].lower() in key.lower():
#verificamos que tenga la mayor parte del contenido
if len(words[0]) >= len(key) / 2 and len(words[0]) != 1:
#checamos hasta la coma
if ',' in greeting[i]:
#eliminamos desde el greeting hasta la coma
index = greeting[i].find(',')
#sentence = sentence.replace('\n', ' ')
substring = greeting[i]
#print(substring[0:index+1])
sentence = sentence.replace(substring[0:index+1], '')
sentence = RemoveWhiteSpaces(sentence)
else:
#si todo es mayor que tres veces el greeting
if len(greeting[i]) >= len(words[0]) * 3:
#se elimina solo el greeting
index = greeting[i].lower().find(words[0].lower())
substring = greeting[i]
#sentence = sentence.replace(words[0], '')
sentence = sentence.replace(substring[index:len(words[0])], '')
sentence = RemoveWhiteSpaces(sentence)
else:
#se elimina todo
sentence = sentence.replace(greeting[i], '')
sentence = RemoveWhiteSpaces(sentence)
#encontró el greeting, nos salimos del ciclo
break
else:
#todos los posibles greetings que tienen cambios de formato
if key.lower() in words[0].lower():
#checamos hasta la coma
if ',' in greeting[i]:
#eliminamos desde el greeting hasta la coma
index = greeting[i].find(',')
#sentence = sentence.replace('\n', ' ')
substring = greeting[i]
#print(substring[0:index+1])
sentence = sentence.replace(substring[0:index+1], '')
sentence = RemoveWhiteSpaces(sentence)
else:
#checamos que empiece con el greeting
index = greeting[i].lower().find(key.lower())
#Si empieza con el greeting
if index == 0:
#si es 2/3 de la palabra
if len(key) >= len(words[0]) * 0.666:
#eliminamos este greeting
index = greeting[i].lower().find(words[0].lower())
substring = greeting[i]
#sentence = sentence.replace(words[0], '')
sentence = sentence.replace(substring[index:len(words[0])], '')
sentence = RemoveWhiteSpaces(sentence)
#encontró el greeting, nos salimos del ciclo
break
return sentence
except TypeError:
print(sentence)
return sentence
def RemoveFarewells(sentence, farewells):
breakBool = False
try:
#checamos si tiene formato
if '\n' in sentence:
#hacemos el split
farewell = sentence.split('\n')
#pensar en una forma para poder checar el penúltimo también
#muchas veces ponen Thank you y luego firman con su nombre
for line in farewell:
for f in farewells:
if f.lower() in line.lower():
#aqui nos detenemos y cortamos todo
#validamos la linea que sea
if line != farewell[0]:
#no es la primera linea
#checamos la posición del farewell
index = line.lower().find(f.lower())
if index >= len(line) / 2:
#el farewell está pasando la mitad de la linea
#cortamos del farewell al final
substring = sentence[sentence.lower().find(f.lower()):]
sentence = sentence.replace(substring, '')
sentence = RemoveWhiteSpaces(sentence)
breakBool = True
break
else:
#se elimina toda la linea y hasta el final
substring = sentence[sentence.lower().find(line.lower()):]
sentence = sentence.replace(substring, '')
sentence = RemoveWhiteSpaces(sentence)
breakBool = True
break
if breakBool:
break
return sentence
except TypeError:
return sentence
# vamos a eliminar cambios en formatos e imperfecciones
def RemoveImperfections(sentence):
try:
# checamos los cambios en el formato (remove tabs and enters)
if '\t' in sentence:
sentence = sentence.replace('\t', ' ')
if '\n' in sentence:
sentence = sentence.replace('\n', ' ')
if '"' in sentence:
sentence = sentence.replace('"', '')
if "'" in sentence:
sentence = sentence.replace("'", '')
if '|' in sentence:
sentence = sentence.replace('|', ' ')
# checamos que tenga un espacio después de
if '..' in sentence:
sentence = sentence.replace('..', '.')
if ',' in sentence:
sentence = sentence.replace(',', ', ')
if ' ,' in sentence:
sentence = sentence.replace(' ,', ',')
if ';' in sentence:
sentence = sentence.replace(';', '; ')
if '-->' in sentence:
sentence = sentence.replace('-->', ' ')
if '>' in sentence:
sentence = sentence.replace('>', ' ')
if '<' in sentence:
sentence = sentence.replace('<', ' ')
if '->' in sentence:
sentence = sentence.replace('->', ' ')
if ' + ' in sentence:
sentence = sentence.replace(' + ', ' and ')
if ' & ' in sentence:
sentence = sentence.replace(' & ', ' and ')
if ' - ' in sentence:
sentence = sentence.replace(' - ', ' ')
# if ':' in sentence:
# sentence = sentence.replace(':', ': ')
if ' :' in sentence:
sentence = sentence.replace(' :', ': ')
if ' : ' in sentence:
sentence = sentence.replace(' : ', ': ')
if ' .' in sentence:
sentence = sentence.replace(' .', '.')
if '(' in sentence:
#sentence = sentence.replace('(', ' ( ')
sentence = sentence.replace('(', '')
if ')' in sentence:
#sentence = sentence.replace(')', ' ) ')
sentence = sentence.replace(')', '')
if 'pls' in sentence:
sentence = sentence.replace('pls', 'please')
if 'Pls' in sentence:
sentence = sentence.replace('Pls', 'Please')
if 'pls.' in sentence:
sentence = sentence.replace('pls.', 'please')
if 'Pls.' in sentence:
sentence = sentence.replace('Pls.', 'Please')
# quitamos todo doble espacio que pudimos haber causado
if " " in sentence:
sentence = sentence.replace(" ", " ")
if " " in sentence:
sentence = sentence.replace(" ", " ")
return sentence
except TypeError:
return sentence
def RemoveDoubleSpaces(sentence):
if " " in sentence:
sentence = sentence.replace(" ", " ")
if " " in sentence:
sentence = sentence.replace(" ", " ")
return sentence
def RemoveWhiteSpaces(word):
try:
if word[0] == ' ':
word = word[1:]
return RemoveWhiteSpaces(word)
else:
if word[len(word) - 1] == ' ':
word = word[:len(word) - 2]
return RemoveWhiteSpaces(word)
else:
return word
except IndexError:
# print('Remove White Spaces catch', word, len(word))
return word
def CleaningCorpora(nlp, file, vocab_size):
nlp = en_core_web_sm.load()
corpus_preprocessed = [] # texto preprocesado
corpus_raw = [] # texto original
entities = {} # xxx potenciales
hyphEntities = {}
for index in range(0, vocab_size):
corpus_raw.append(file.iat[index, 0])
preprocessed = RemoveImperfections(corpus_raw[index])
sentence = nlp(preprocessed)
i = 0 # contadores auxiliares para encontrar parejas NNP
hyphFlag = False
# POS Tagger
NPPwords = []
for token in sentence:
# se agrega uno a i aunque no sea NNP
i = i + 1
# checamos otro tipo de token
if token.text == '-':
hyphFlag = True
else:
text = token.text
if text[len(text) - 1] == ':':
try:
# el token que sigue será la entity
wordToken = RemoveWhiteSpaces(sentence[i].text.lower())
NPPwords.append(wordToken)
# entities = SaveEntities(sentence[i + 1].text.lower(), entities)
except IndexError:
pass
# token.tag_ == 'HYPH'
if token.tag_ == 'NNP' and token.text != '-':
# checamos que no sea el primero
if i == len(sentence):
# checamso que no sea la del después de los :
if len(NPPwords) >= 1:
wordToken = RemoveWhiteSpaces(token.text.lower())
if NPPwords[len(NPPwords) - 1] == wordToken:
# lo eliminamos del arreglo, al cabo se vuelve a agregar
# esto es para que no se repita
NPPwords.pop()
# grabamos el NNP en el arreglo
NPPword = RemoveWhiteSpaces(token.text.lower())
NPPwords.append(NPPword)
# es la última, entonces se graba
NPPword = ''
if len(NPPwords) > 1:
NPPword = NPPwords[len(NPPwords) - 1] + ' '
NPPwords.pop()
for word in reversed(NPPwords):
NPPword += word + ' '
else:
NPPword = NPPwords[0]
NPPword = RemoveWhiteSpaces(NPPword)
if len(NPPword) > 0:
# mandamos como token los NPPs
entities = SaveEntities(NPPword, entities)
# limpiamos el arreglo
NPPwords = []
else:
# es el primero
NPPword = RemoveWhiteSpaces(token.text.lower())
NPPwords.append(NPPword)
else:
# no es NPP
# grabamos los NPPwords que llegamos
if len(NPPwords) != 0:
NPPword = ''
if len(NPPwords) > 1:
NPPword = NPPwords[len(NPPwords) - 1] + ' '
NPPwords.pop()
for word in reversed(NPPwords):
NPPword += word + ' '
else:
NPPword = NPPwords[0]
NPPword = RemoveWhiteSpaces(NPPword)
if len(NPPword) > 0:
# mandamos como token los NPPs
entities = SaveEntities(NPPword, entities)
# limpiamos el arreglo
NPPwords = []
# else no hay nada que grabar
if token.is_stop:
# la eliminamos del texto
preprocessed = preprocessed.replace(' ' + token.text + ' ', ' ')
# eliminamos posibles cambios de formato
preprocessed = RemoveDoubleSpaces(preprocessed)
# ya se termino de procesar la palabra
# sacamos los posibles entities obtenidos de los -
if hyphFlag:
posEntities = HYPHEntity(preprocessed)
for posEntity in posEntities:
if posEntity in hyphEntities:
hyphEntities.update({posEntity: hyphEntities[posEntity] + 1})
else:
hyphEntities.update({posEntity: 1})
entities = SaveEntities(posEntity, entities)
corpus_preprocessed.append(preprocessed)
# filtramos el dictionary
filterBy = [' ', '/', '\\', '.', '_', '-', '+', ',', ':'] # filtramos por varios requisitos
for filterParam in filterBy:
entities = FilterEntities(entities, filterParam)
# ordenamos el diccionario
# sorted(entities.values())
# quiero ver los datos
after = SeeData(entities)
# vamos a eliminar todos los que tengan frecuencia 1
# a excepcion de los alfanumericos o numericos
entities = DeleteEntities(entities)
before = SeeData(entities)
# eliminamos todos los que son parte de las entidades de los '-'
# checamos si existen solas o si alguna contiene otra
repeatedEntities = {}
for hyphEntity in hyphEntities:
separatedEntity = hyphEntity.split('-')
for entity in separatedEntity:
if entity in entities:
# si existe por si sola
# hay que eliminarla
del entities[entity]
else:
# checamos si lo contiene
for key, value in entities.items():
if entity in key:
repeatedEntities.update({key: value})
# del entities[key]
# for key in repeatedEntities:
# del entities[key]
data = {
"corpus_preprocessed": corpus_preprocessed,
"corpus_raw": corpus_raw,
"entities": entities,
"after": after,
"before": before,
"hyphEntities": hyphEntities,
"repeatedEntities": repeatedEntities
}
return data
def CleaningCorporaTwo(nlp, file, vocab_size):
nlp = en_core_web_sm.load()
corpus_preprocessed = [] # texto preprocesado
corpus_raw = [] # texto original
entities = {} # xxx potenciales
hyphEntities = {}
verbList = {} #lista de verbos
new_verbs = {} #dic de verbos nuevos
word_data = {} #ver como quedo la palabra
#lista de verbos
verb_text = FetchInfo("C:/Users/carlos.ortega/Source/Repos/AutomationPlatform/TuringExpo/bin/Debug/Python/Datasets/verbs.txt")
verb_list = verb_text.read().split('\n')
verbs = {}
for i in range(0, len(verb_list) - 1):
verbs.update({ verb_list[i]: 0})
for index in range(0, vocab_size):
corpus_raw.append(file.iat[index, 0])
preprocessed = RemoveImperfections(corpus_raw[index])
sentence = nlp(preprocessed)
i = 0 # contadores auxiliares para encontrar parejas NNP
hyphFlag = False
# POS Tagger
NPPwords = []
for token in sentence:
# se agrega uno a i aunque no sea NNP
i = i + 1
# checamos otro tipo de token
if token.text == '-':
hyphFlag = True
else:
text = token.text
if text[len(text) - 1] == ':':
try:
# el token que sigue será la entity
wordToken = RemoveWhiteSpaces(sentence[i].text.lower())
NPPwords.append(wordToken)
# entities = SaveEntities(sentence[i + 1].text.lower(), entities)
except IndexError:
pass
# token.tag_ == 'HYPH'
if token.tag_ == 'NNP' and token.text != '-':
# checamos que no sea el primero
if i == len(sentence):
# checamso que no sea la del después de los :
if len(NPPwords) >= 1:
wordToken = RemoveWhiteSpaces(token.text.lower())
if NPPwords[len(NPPwords) - 1] == wordToken:
# lo eliminamos del arreglo, al cabo se vuelve a agregar
# esto es para que no se repita
NPPwords.pop()
# grabamos el NNP en el arreglo
NPPword = RemoveWhiteSpaces(token.text.lower())
NPPwords.append(NPPword)
# es la última, entonces se graba
NPPword = ''
if len(NPPwords) > 1:
NPPword = NPPwords[len(NPPwords) - 1] + ' '
NPPwords.pop()
for word in reversed(NPPwords):
NPPword += word + ' '
else:
NPPword = NPPwords[0]
NPPword = RemoveWhiteSpaces(NPPword)
if len(NPPword) > 0:
# mandamos como token los NPPs
entities = SaveEntities(NPPword, entities)
# limpiamos el arreglo
NPPwords = []
else:
# es el primero
NPPword = RemoveWhiteSpaces(token.text.lower())
NPPwords.append(NPPword)
else:
# no es NPP
# grabamos los NPPwords que llegamos
if len(NPPwords) != 0:
NPPword = ''
if len(NPPwords) > 1:
NPPword = NPPwords[len(NPPwords) - 1] + ' '
NPPwords.pop()
for word in reversed(NPPwords):
NPPword += word + ' '
else:
NPPword = NPPwords[0]
NPPword = RemoveWhiteSpaces(NPPword)
if len(NPPword) > 0:
# mandamos como token los NPPs
entities = SaveEntities(NPPword, entities)
# limpiamos el arreglo
NPPwords = []
# else no hay nada que grabar
if token.pos_ == 'VERB':
if '/' in token.text or '-' in token.text or '\\' in token.text or '.' in token.text:
#vemos si podemos partir el token
aux = SplitData(token.text.lower(), verbs, nlp)
if 'word' in aux.keys():
preprocessed = preprocessed.replace(' ' + aux['word'] + ' ', ' ')
word_data.update({ aux["word"]: 0 })
if 'new_verbs' in aux.keys():
for new in aux["new_verbs"]:
if new not in new_verbs:
new_verbs.update({ new: 0 })
else:
preprocessed = preprocessed.replace(' ' + token.text + ' ', ' ')
if token.lemma_ not in verbList:
#lo agregamos
verbList.update({ token.lemma_: 1 })
else:
#ya existe
verbList.update({ token.lemma_: verbList[token.lemma_] + 1 })
# eliminamos posibles cambios de formato
# ya se termino de procesar la palabra
# sacamos los posibles entities obtenidos de los -
if hyphFlag:
posEntities = HYPHEntity(preprocessed)
for posEntity in posEntities:
if posEntity in hyphEntities:
hyphEntities.update({posEntity: hyphEntities[posEntity] + 1})
else:
hyphEntities.update({posEntity: 1})
entities = SaveEntities(posEntity, entities)
corpus_preprocessed.append(preprocessed)
# filtramos el dictionary
filterBy = [' ', '/', '\\', '.', '_', '-', '+', ',', ':'] # filtramos por varios requisitos
for filterParam in filterBy:
entities = FilterEntities(entities, filterParam)
# ordenamos el diccionario
# sorted(entities.values())
# quiero ver los datos
after = SeeData(entities)
# vamos a eliminar todos los que tengan frecuencia 1
# a excepcion de los alfanumericos o numericos
entities = DeleteEntities(entities)
before = SeeData(entities)
# eliminamos todos los que son parte de las entidades de los '-'
# checamos si existen solas o si alguna contiene otra
repeatedEntities = {}
for hyphEntity in hyphEntities:
separatedEntity = hyphEntity.split('-')
for entity in separatedEntity:
if entity in entities:
# si existe por si sola
# hay que eliminarla
del entities[entity]
else:
# checamos si lo contiene
for key, value in entities.items():
if entity in key:
repeatedEntities.update({key: value})
# del entities[key]
# for key in repeatedEntities:
# del entities[key]
data = {
"corpus_preprocessed": corpus_preprocessed,
"corpus_raw": corpus_raw,
"entities": entities,
"after": after,
"before": before,
"hyphEntities": hyphEntities,
"repeatedEntities": repeatedEntities,
"verbList": verbList,
"verbs": verbs,
"new_verbs": new_verbs,
"word_data": word_data
}
return data
def CleaningCorporaThree(nlp, file, vocab_size, base_path):
nlp = en_core_web_sm.load()
corpus_preprocessed = [] # texto preprocesado
corpus_raw = [] # texto original
entities = {} # xxx potenciales