#!/usr/bin/python # -*- coding: utf-8 -*- #Autor: Erickson Silva #Email: #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