AplicaRegras.py 5.63 KB
#!/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 LeitorDicionarios import *
from Iterator import *
from StringAux import *
from ConversorExtenso import *
from collections import deque

class AplicaRegras(object):

	# inicializa todos as variaveis
	def __init__(self):	
		self.__dicionarios = LeitorDicionarios()

	# 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