AplicaRegras.py
9.54 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Autor: Erickson Silva
#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
#LAViD - Laboratório de Aplicações de Vídeo Digital
from collections import deque
import xml.etree.ElementTree as ET
from os.path import expanduser
import platform
from LeitorDicionarios import *
from Iterator import *
from StringAux import *
from ConversorExtenso import *
class AplicaRegras(object):
# inicializa todos as variaveis
def __init__(self):
self.__root = self.getRoot()
self.__dicionarios = LeitorDicionarios()
def getRoot(self):
so = platform.system()
if so == 'Windows':
return ET.parse(expanduser("~")+'\\vlibras-translate\data\\regras.xml').getroot()
else:
return ET.parse(expanduser("~")+'/vlibras-translate/data/regras.xml').getroot()
def aplicarRegrasMorpho(self, lista):
self.__especificos = {"advt" : self.verificarAdvTempo, "v" : self.verificarVbInfinitivo, "x" : self.verificarPrepos, "c" : self.verificarSubs2Generos, "a" : self.verificarArtigo, "l" : self.verificarVbLigacao, "i": self.verificarAdvIntensidade, "vbi":"zero", "n":"zero", "abmn":"zero", "adji":"zero", "adjn":"zero", "advi":"zero"}
self.pularIteracoes = 0
self.__tAux = []
it = Iterator()
it.load(lista)
while(it.hasNext()):
if self.pularIteracoes > 0:
self.pularIteracoes-=1
continue
for morpho in self.__root.findall('morphological'):
self.hasRule = False
for rule in morpho.findall('rule'): # procura a tag rule
if rule.find('active').text == "true" and rule.get('name').split("_")[0] == it.getAtualT():
count = int(rule.find('count').text)
self.listaIter = []
if count == 1:
self.listaIter = [it.getToken()]
else:
try:
self.listaIter = it.getInterval(count)
self.pularIteracoes = count-1
except:
continue
self.nomeRegra = self.gerarNomeDaRegra(self.listaIter)
if rule.get('name') == self.nomeRegra: # verifica se a regra é aplicavel e a mesma esta ativa
print "Achou regra: " + self.nomeRegra
#subIter = Iterator()
#subIter.load(self.listaIter)
#while(subIter.hasNext()):
self.hasRule = True
self.listaTmp = count * [None]
self.countListaIter = -1
for classe in rule.iter('class'): # for nas tags class
title = classe.find('title')
newpos = classe.find('newpos')
newprop = classe.find('newprop')
newtoken = classe.find('newtoken')
newtokenpos = classe.find('newtokenpos')
self.specific = classe.find('specific')
self.countListaIter += 1
token = self.listaIter[self.countListaIter]
if self.specific is not None:
self.specific = self.__especificos[self.specific.text](token[0])
if newprop is not None and type(self.specific) != bool:
self.__tAux.append([self.specific,newprop.text])
if newpos is not None:
if newpos.text != "-1":
if type(self.specific) == bool:
self.listaTmp[int(newpos.text)] = token
else:
self.__tAux.append([self.specific, title.text])
if newtoken is not None:
self.listaTmp[int(newtokenpos.text)] = [newtoken.text, "NEWTOKEN"]
self.listaTmp = filter(None, self.listaTmp)
for i in self.listaTmp:
self.__tAux.append(i)
break
if (self.hasRule == False): self.__tAux.append(it.getToken())
if self.__tAux: return self.__tAux
return lista # retorna a lista sem alteracoes (nao existe regra)
def gerarNomeDaRegra(self, lista):
self.__nomeRegra = []
for t in lista:
self.__nomeRegra.append(t[1])
return "_".join(self.__nomeRegra)
def verificarAdvTempo(self, lista):
for i in lista:
if i[1][:3] == "ADV":
if (self.__dicionarios.hasTempoVerbal(i[0])):
return True
return False
def verificarVbInfinitivo(self, token):
if self.__dicionarios.hasVerboInfinitivo(token): # verifica se ha um verbo infinitivo desse token
return self.__dicionarios.getVerboInfinitivo(token)
return False
#TODO
def verificarPrepos(self, token):
return None
def verificarSubs2Generos(self, token):
return self.__dicionarios.hasSubst2Genero(token)
#TODO
def verificarArtigo(self, token):
return None
#TODO
def verificarVbLigacao(self, token):
return None
#TODO
def verificarAdvIntensidade(self, token):
return None
# retira artigos e preposicoes; passa verbos para infinitivo e verificar se há sinonimos
def inicializar(self, texto):
it = Iterator()
it.load(texto)
self.__ts = []
self.__verb = False
self.__adv = False
self.__num = False
self.__plural = False
self.__countVerb = 0
self.__countAdv = 0
while(it.hasNext()):
token = it.getAtualW()
tag = it.getAtualT()
self.__b = False
if self.__dicionarios.hasPalavraIgnorada(tag) == False: # verifica se nao eh artigo/preposicao
if tag == "NUM":
self.__num = True
if tag[-2:] == "-P":
self.__plural = True
#VERIFICA SE É ADVERBIO E CONTA A QUANTIDADE
if tag[:3] == "ADV":
if (self.__dicionarios.hasTempoVerbal(token)):
self.__adv = True
if tag[:2] == "VB":
#VERIFICA SE É VERBO NO INFINITIVO
if self.__dicionarios.hasVerboInfinitivo(token): # verifica se ha um verbo infinitivo desse token
verboInfinitivo = self.__dicionarios.getVerboInfinitivo(token) # se sim, adiciona numa string aux
self.__ts.append([verboInfinitivo,tag]) # caso contrario, adiciona so o verbo infinitivo msm
self.__b = True
#VERIFICA SE É VERBO DE TEMPO E CONTA A QUANTIDADE
if tag == "VB-P" or tag == "VB-D" or tag == "VB-R":
self.__verb = True
self.__countVerb += 1
#VERIFICA SE É SUBTANTIVO COMUM DOS 2 GENEROS
if self.__dicionarios.hasSubst2Genero(token):
#del self.__ts[-1]
lenTicket = len(it.getAntT())
if ((self.__dicionarios.hasPalavraIgnorada(it.getAntT())) and (it.getAntT()[lenTicket-1:] == "F") or (it.getAntT()[lenTicket-3:] == "F-P")):
self.__ts.append(["MULHER ", "2GEN"])
self.__ts.append([token,tag])
else:
self.__ts.append(["HOMEM ", "2GEN"])
self.__ts.append([token,tag])
self.__b = True
#SE NÃO HOUVE NENHUM ALTERAÇÃO, OU SEJA, NÃO APLICOU NENHUMA REGRA, ADICIONA O TOKEN ORIGINAL
if self.__b == False: # verifica se nao encontrou nem verbo infinito ou sinonimo
self.__ts.append([token,tag])
#SE ENCONTROU VERBO, ENTÃO ANALISA a SENTENCA NOVAMENTE (again?)
if self.__verb == True and self.__adv == False:
self.__ts = self.verbalAnalysis(self.__ts)
#VERIFICA SE É PLURAL
if self.__plural:
self.__ts = self.hasPlural(self.__ts)
#CONVERTE EXTENSO PARA NUMERO
if self.__num: return self.converteExtenso(self.__ts)
return self.__ts
# converte romano para numero
def auxConvert(self, tag):
try:
return roman_to_int(tag)
except:
return tag
def verbalAnalysis(self, lista):
lv = []
it = Iterator()
it.load(lista)
hasFut = False
hasPas = False
count = 0
while(it.hasNext()):
token = it.getAtualW().upper()
tag = it.getAtualT()
if(tag == "VB-P"):
if (self.__countVerb > 1):
count += 1
#print "VB-P: Incrementou"
if(count == self.__countVerb):
#print "VB-P Adicionou " + token
lv.append([token,tag])
else:
#print "VB-P: retornou lista original"
it.reset()
return lista
elif(tag == "VB-D"):
count += 1
hasPas = True
#print "VB-D: Incrementou"
if(count == self.__countVerb):
#print "VB-D Adicionou " + token
lv.append([token,tag])
elif(tag == "VB-R"):
count += 1
hasFut = True
#print "VB-R: Incrementou"
if(count == self.__countVerb):
#print "VB-R Adicionou " + token
lv.append([token,tag])
else:
lv.append([token,tag])
if (hasFut):
lv.append(["FUTURO", "T-VB"])
elif (hasPas):
lv.append(["PASSADO", "T-VB"])
it.reset()
return lv
def hasPlural(self, lista):
tmp = lista
for e in tmp:
if e[1][-2:] == "-P":
e[0] = self.analisarPlural(e[0])
return tmp
def analisarPlural(self, word):
if(word[-3:] == "OES" or word[-2:] == "AES" or word[-2:] == "AOS"):
return word[0:-3]+"AO"
elif(word[-3:] == "RES" or word[-2:] == "ZES" or word[-2:] == "NES"):
return word[0:-2]
elif(word[-3:] == "SES"):
#TODO: Algumas palavras possuem marcações gráficas na raiz singular. Ex: Gás – Gases
return word[0:-2]
elif(word[-2:] == "NS"):
return word[0:-2]+"M"
elif(word[-3:] == "EIS"):
return word[0:-3]+"IL"
elif(word[-2:] == "IS"):
if(word[-3] == "A" or word[-3] == "E" or word[-3] == "O" or word[-3] == "U"):
return word[0:-2]+"L"
else:
return word
elif(word[-1] == "S"):
#TODO: Palavras paroxítonas ou proparoxítonas terminadas em S. Ex: lápis, vírus, tagênis, ônibus, etc
return word[0:-1]
else:
return word
def converteExtenso(self, lista):
listAux = []
indexDel = []
count = 0
isRunning = False
for i in range(0, len(lista)):
token = lista[i][0]
tag = lista[i][1]
if (tag == "NUM"):
if (isRunning == False and len(listAux) == count):
listAux.append([i,[token]])
isRunning = True
else:
listAux[count][1].append(token)
indexDel.append(i)
elif (isRunning == True):
if ((lista[i-1][1] == "NUM") and (lista[i+1][1] == "NUM") and (tag == "CONJ")):
indexDel.append(i)
else:
isRunning = False
count += 1
for i in listAux:
ext = extenso(' '.join(i[1]))
lista[i[0]] = [ext, "NUM"]
deque((list.pop(lista, i) for i in sorted(indexDel, reverse=True)), maxlen=0)
return lista