Ejemplo n.º 1
0
def process(sentence):
    t = parsetree(sentence, lemmata=True)
    m=pattern_utils.pattern_match("que {VP} {NP}", t)
    if m:
        n, g, noun = pattern_utils.parse_NP(m.group(2))
        r=dict()
        r['type']='query'
        r['question']='que'
        r["relation"]=conjugate(m.group(1).string, INFINITIVE)
        r['gender']=g
        r['object']=noun
        return r

    m=pattern_utils.pattern_match("como {VP} {NP}", t)
    if m:
        n, g, noun = pattern_utils.parse_NP(m.group(2))
        r=dict()
        r['type']='query'
        r['question']='como'
        r["relation"]=conjugate(m.group(1).string, INFINITIVE)
        r['gender']=g
        r['object']=noun
        return r

    return None
Ejemplo n.º 2
0
    def filter_pos_infinitive(self, s, category_list=[], allowed=False):
            '''
              Filters grammatical categories (pos:Part-of-Speech tags) from a string
              and converts to infinitive, predicative and singularized forms words:

              If allowed is set to True it only allows POS in category_list.
              If allowed is set to False it allows all POS except those in category_list

              POS that can be in category list: 
              nouns        = ['NN', 'NNS', 'NNP', 'NNPS']
              verbs        = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']
              adjectives   = ['JJ','JJR','JJS']
              determiners  = ['DT']
              conjunctions = ['IN', 'CC']
              adverbs      = ['RB','RBR', 'RBS']
              modals       = ['MD']
              utterances   = ['UH']

              In:
                  (s:string, category_list:list of strings, allowed:boolean)
              Out:
                  (string)
            '''
            if isinstance(s, str):
                s = unicode(s, "utf-8", "xmlcharrefreplace")
            list = []
            pos_list = self.pos_tagging(s)
            if len(category_list) == 0:
                return s
            if allowed == False:
                for pos in pos_list:
                    if pos.split(':')[1] not in category_list:
                        if pos.split(':')[1] in ['NNS']:
                            word = singularize(pos.split(':')[0])  
                            list.append(word)
                        elif pos.split(':')[1] in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
                            word = conjugate(pos.split(':')[0], INFINITIVE)  
                            list.append(word)
                        elif pos.split(':')[1] in ['JJ','JJR','JJS']:
                            word = predicative(pos.split(':')[0])  
                            list.append(word)
                        else:
                            list.append(pos.split(':')[0])
            else:
                for pos in pos_list:
                    if pos.split(':')[1] in category_list:
                        if pos.split(':')[1] in ['NNS']:
                            word = singularize(pos.split(':')[0])  
                            list.append(word)
                        elif pos.split(':')[1] in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
                            word = conjugate(pos.split(':')[0], INFINITIVE)  
                            list.append(word)
                        elif pos.split(':')[1] in ['JJ','JJR','JJS']:
                            word = predicative(pos.split(':')[0])  
                            list.append(word)
                        else:
                            list.append(pos.split(':')[0])
            return u' '.join(list)
Ejemplo n.º 3
0
 def test_tenses(self):
     # Assert tense recognition.
     self.assertTrue((es.PRESENT, 3, es.SG) in es.tenses("es"))
     self.assertTrue("2sg" in es.tenses("eres"))
     # The CONDITIONAL is sometimes described as a mood, 
     # and sometimes as a tense of the indicative mood (e.g., in Spanish):
     t1 = (es.CONDITIONAL, 1, es.SG)
     t2 = (es.PRESENT, 1, es.SG, es.CONDITIONAL)
     self.assertTrue("1sg->" in es.tenses(u"sería"))
     self.assertTrue(t1 in es.tenses(u"sería"))
     self.assertTrue(t2 in es.tenses(u"sería"))
     self.assertTrue(t1 in es.tenses(es.conjugate("ser", mood=es.INDICATIVE, tense=es.CONDITIONAL)))
     self.assertTrue(t2 in es.tenses(es.conjugate("ser", mood=es.CONDITIONAL)))
     print("pattern.es.tenses()")
Ejemplo n.º 4
0
 def test_tenses(self):
     # Assert tense recognition.
     self.assertTrue((es.PRESENT, 3, es.SG) in es.tenses("es"))
     self.assertTrue("2sg" in es.tenses("eres"))
     # The CONDITIONAL is sometimes described as a mood,
     # and sometimes as a tense of the indicative mood (e.g., in Spanish):
     t1 = (es.CONDITIONAL, 1, es.SG)
     t2 = (es.PRESENT, 1, es.SG, es.CONDITIONAL)
     self.assertTrue("1sg->" in es.tenses(u"sería"))
     self.assertTrue(t1 in es.tenses(u"sería"))
     self.assertTrue(t2 in es.tenses(u"sería"))
     self.assertTrue(t1 in es.tenses(
         es.conjugate("ser", mood=es.INDICATIVE, tense=es.CONDITIONAL)))
     self.assertTrue(
         t2 in es.tenses(es.conjugate("ser", mood=es.CONDITIONAL)))
     print("pattern.es.tenses()")
Ejemplo n.º 5
0
    def pos_tagging_infinitive(self, s):
            '''
              Grammatical category of each word a.k.a. Part-of-Speech (pos) tagging,
              but transformming adjectives to predicative form, singularizing nouns and
              verbs to infinitive form

              ej. ella:PRP maneja:VBD carros:NNS rojos:JJ
                    PRP: Possesive pronoun  ---> ella
                    VBD: Verb in past tense ----> manejar(infinitive)
                    NNS: Noun in plural --------> carro (singularized)
                    JJ: adjective --------------> rojo (predicative)
              In:
                    (s:string) string text               
              Out:
                    (list) list with grammatical categories in the form 'word:category'
            '''
            categories = parse(s)
            list = []
            if isinstance(s, str):
                s = unicode(s, "utf-8", "xmlcharrefreplace")
            for x in categories.split():
                for y in x:
                    if y[1] in ['NNS']:
                        word = singularize(y[0])  
                        list.append(word+":NN")
                    elif y[1] in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
                        word = conjugate(y[0], INFINITIVE)  
                        list.append(word+":VB")
                    elif y[1] in ['JJ','JJR','JJS']:
                        word = predicative(y[0])  
                        list.append(word+":JJ")
                    else:
                        list.append(y[0]+':'+y[1])
            return list
Ejemplo n.º 6
0
def verbosInfinitivos(cadena):
    lista = []
    palabras = parse(cadena).split()
    for x in palabras:
        for y in x:
            if ((y[1] == 'VB') or (y[1]) == 'VBI'):
                lista.append(conjugate(y[0], INFINITIVE))
    return lista
Ejemplo n.º 7
0
def verbosInfinitivos(str):
    verbos = []
    for word, pos in tag(
            str
    ):  #tag devuelve una lista de tuplas formadas por (palabra, tipo de palabra)
        if pos == "VB":
            verbos.append(conjugate(word, tense=INFINITIVE))
    return verbos
Ejemplo n.º 8
0
def verbosInfinitivos(cadena):
    lista = []
    palabras = parse(cadena).split()
    for x in palabras:
        for y in x:
             if ((y[1] == 'VB') or (y[1])=='VBI'):
                 lista.append(conjugate(y[0],INFINITIVE))
    return lista
Ejemplo n.º 9
0
def crearTexto():
    for x in pattern.es.lexicon.keys():
        if x in pattern.es.spelling.keys():
            s = (pattern.es.parse(x).split())
            for cada in s:
                for c in cada:
                    if c[1] == 'VB':
                        palabra = conjugate(x, INFINITIVE)
                        lista_palabras.append(palabra)
Ejemplo n.º 10
0
def verbos_infinitivos(oracion):
    lista_infinitivos = []
    oracion = tag(
        oracion
    )  # Devuelve una tupla con el siguiente formato: (palabra,tipo) -- tipo: adjetivo,verbo,etc.
    for palabra, tipo in oracion:
        if (tipo == 'VB'):  # Veo cuales son los verbos
            lista_infinitivos.append(conjugate(palabra, INFINITIVE))
    return lista_infinitivos
Ejemplo n.º 11
0
 def test_parse_lemma(self):
     # Assert the accuracy of the verb lemmatization algorithm.
     i, n = 0, 0
     for v in es.inflect.VERBS.infinitives:
         for tense in es.inflect.VERBS.TENSES:
             if es.inflect._parse_lemma(es.conjugate(v, tense)) == v: 
                 i += 1
             n += 1
     self.assertTrue(float(i) / n > 0.80)
     print "pattern.es.inflect._parse_lemma()"
Ejemplo n.º 12
0
def generate_light_verb_phrase(light_verb, word_match, noun, internal_str=''):
    word_match_tense = tenses(word_match)[0]
    conjugated_light_verb = conjugate(light_verb, word_match_tense)
    #     if(determiner):
    #         light_verb_phrase = '%s un %s'%(conjugated_light_verb, noun)
    #     else:
    #         light_verb_phrase = '%s %s'%(conjugated_light_verb, noun)
    if (internal_str != ''):
        light_verb_phrase = f'{conjugated_light_verb} {internal_str} {noun}'
    else:
        light_verb_phrase = f'{conjugated_light_verb} {noun}'
    return light_verb_phrase
Ejemplo n.º 13
0
def infinitivo(str):
    """Recibe un string. Devuelve una lista de verbos en infinitivo."""

    resultado = []
    listaVerbos = parse(str).split()
    # The output of parse() is a string of sentences in which each word has been annotated with the requested tags.
    for nivel2 in listaVerbos:
        for codigo in nivel2:
            if codigo[1] == 'VB' or codigo[1] == 'VBG':
                resultado.append(conjugate(codigo[0], tense=INFINITIVE))

    return resultado
Ejemplo n.º 14
0
 def test_conjugate(self):
     # Assert different tenses with different conjugations.
     for (v1, v2, tense) in (
         ("ser", u"ser", es.INFINITIVE),
         ("ser", u"soy", (es.PRESENT, 1, es.SINGULAR)),
         ("ser", u"eres", (es.PRESENT, 2, es.SINGULAR)),
         ("ser", u"es", (es.PRESENT, 3, es.SINGULAR)),
         ("ser", u"somos", (es.PRESENT, 1, es.PLURAL)),
         ("ser", u"sois", (es.PRESENT, 2, es.PLURAL)),
         ("ser", u"son", (es.PRESENT, 3, es.PLURAL)),
         ("ser", u"siendo", (es.PRESENT + es.PARTICIPLE)),
         ("ser", u"sido", (es.PAST + es.PARTICIPLE)),
         ("ser", u"era", (es.IMPERFECT, 1, es.SINGULAR)),
         ("ser", u"eras", (es.IMPERFECT, 2, es.SINGULAR)),
         ("ser", u"era", (es.IMPERFECT, 3, es.SINGULAR)),
         ("ser", u"éramos", (es.IMPERFECT, 1, es.PLURAL)),
         ("ser", u"erais", (es.IMPERFECT, 2, es.PLURAL)),
         ("ser", u"eran", (es.IMPERFECT, 3, es.PLURAL)),
         ("ser", u"fui", (es.PRETERITE, 1, es.SINGULAR)),
         ("ser", u"fuiste", (es.PRETERITE, 2, es.SINGULAR)),
         ("ser", u"fue", (es.PRETERITE, 3, es.SINGULAR)),
         ("ser", u"fuimos", (es.PRETERITE, 1, es.PLURAL)),
         ("ser", u"fuisteis", (es.PRETERITE, 2, es.PLURAL)),
         ("ser", u"fueron", (es.PRETERITE, 3, es.PLURAL)),
         ("ser", u"sería", (es.CONDITIONAL, 1, es.SINGULAR)),
         ("ser", u"serías", (es.CONDITIONAL, 2, es.SINGULAR)),
         ("ser", u"sería", (es.CONDITIONAL, 3, es.SINGULAR)),
         ("ser", u"seríamos", (es.CONDITIONAL, 1, es.PLURAL)),
         ("ser", u"seríais", (es.CONDITIONAL, 2, es.PLURAL)),
         ("ser", u"serían", (es.CONDITIONAL, 3, es.PLURAL)),
         ("ser", u"seré", (es.FUTURE, 1, es.SINGULAR)),
         ("ser", u"serás", (es.FUTURE, 2, es.SINGULAR)),
         ("ser", u"será", (es.FUTURE, 3, es.SINGULAR)),
         ("ser", u"seremos", (es.FUTURE, 1, es.PLURAL)),
         ("ser", u"seréis", (es.FUTURE, 2, es.PLURAL)),
         ("ser", u"serán", (es.FUTURE, 3, es.PLURAL)),
         ("ser", u"sé", (es.PRESENT, 2, es.SINGULAR, es.IMPERATIVE)),
         ("ser", u"sed", (es.PRESENT, 2, es.PLURAL, es.IMPERATIVE)),
         ("ser", u"sea", (es.PRESENT, 1, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"seas", (es.PRESENT, 2, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"sea", (es.PRESENT, 3, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"seamos", (es.PRESENT, 1, es.PLURAL, es.SUBJUNCTIVE)),
         ("ser", u"seáis", (es.PRESENT, 2, es.PLURAL, es.SUBJUNCTIVE)),
         ("ser", u"sean", (es.PRESENT, 3, es.PLURAL, es.SUBJUNCTIVE)),
         ("ser", u"fuera", (es.PAST, 1, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"fueras", (es.PAST, 2, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"fuera", (es.PAST, 3, es.SINGULAR, es.SUBJUNCTIVE)),
         ("ser", u"fuéramos", (es.PAST, 1, es.PLURAL, es.SUBJUNCTIVE)),
         ("ser", u"fuerais", (es.PAST, 2, es.PLURAL, es.SUBJUNCTIVE)),
         ("ser", u"fueran", (es.PAST, 3, es.PLURAL, es.SUBJUNCTIVE)),
     ):
         self.assertEqual(es.conjugate(v1, tense), v2)
     print "pattern.es.conjugate()"
Ejemplo n.º 15
0
def cuentapVerbos(str):
    verbos = []
    for word, pos in tag(
            str
    ):  # tag devuelve una lista de tuplas formadas por (palabra, tipo de palabra)
        if pos == "VB":
            verbos.append(conjugate(word, tense=INFINITIVE))

    string = (' ').join(verbos)
    count = Counter(string.split(' ')).most_common()
    for key in range(3):
        print(count[key][0], count[key][1])
Ejemplo n.º 16
0
def verbosInfinitivos(cadena):
	t = parsetree(cadena)
	verbos = search('VB*', t) 
	#lis=verbos.match.string
	#print 'list: ',lis
	#print #no puedo convertirlo a lista de una??
	lista =[]
	for match in verbos:
		lista.append((match.string , conjugate(match.string, INFINITIVE)))
	#print 'lista for: ',lista
	#print lista[3][1] 
	return lista
Ejemplo n.º 17
0
 def test_conjugate(self):
     # Assert different tenses with different conjugations.
     for (v1, v2, tense) in (
       ("ser", u"ser",        es.INFINITIVE),
       ("ser", u"soy",       (es.PRESENT, 1, es.SINGULAR)),
       ("ser", u"eres",      (es.PRESENT, 2, es.SINGULAR)),
       ("ser", u"es",        (es.PRESENT, 3, es.SINGULAR)),
       ("ser", u"somos",     (es.PRESENT, 1, es.PLURAL)),
       ("ser", u"sois",      (es.PRESENT, 2, es.PLURAL)),
       ("ser", u"son",       (es.PRESENT, 3, es.PLURAL)),
       ("ser", u"siendo",    (es.PRESENT + es.PARTICIPLE)),
       ("ser", u"sido",      (es.PAST + es.PARTICIPLE)),
       ("ser", u"era",       (es.IMPERFECT, 1, es.SINGULAR)),
       ("ser", u"eras",      (es.IMPERFECT, 2, es.SINGULAR)),
       ("ser", u"era",       (es.IMPERFECT, 3, es.SINGULAR)),
       ("ser", u"éramos",    (es.IMPERFECT, 1, es.PLURAL)),
       ("ser", u"erais",     (es.IMPERFECT, 2, es.PLURAL)),
       ("ser", u"eran",      (es.IMPERFECT, 3, es.PLURAL)),
       ("ser", u"fui",       (es.PRETERITE, 1, es.SINGULAR)),
       ("ser", u"fuiste",    (es.PRETERITE, 2, es.SINGULAR)),
       ("ser", u"fue",       (es.PRETERITE, 3, es.SINGULAR)),
       ("ser", u"fuimos",    (es.PRETERITE, 1, es.PLURAL)),
       ("ser", u"fuisteis",  (es.PRETERITE, 2, es.PLURAL)),
       ("ser", u"fueron",    (es.PRETERITE, 3, es.PLURAL)),
       ("ser", u"sería",     (es.CONDITIONAL, 1, es.SINGULAR)),
       ("ser", u"serías",    (es.CONDITIONAL, 2, es.SINGULAR)),
       ("ser", u"sería",     (es.CONDITIONAL, 3, es.SINGULAR)),
       ("ser", u"seríamos",  (es.CONDITIONAL, 1, es.PLURAL)),
       ("ser", u"seríais",   (es.CONDITIONAL, 2, es.PLURAL)),
       ("ser", u"serían",    (es.CONDITIONAL, 3, es.PLURAL)),
       ("ser", u"seré",      (es.FUTURE, 1, es.SINGULAR)),
       ("ser", u"serás",     (es.FUTURE, 2, es.SINGULAR)),
       ("ser", u"será",      (es.FUTURE, 3, es.SINGULAR)),
       ("ser", u"seremos",   (es.FUTURE, 1, es.PLURAL)),
       ("ser", u"seréis",    (es.FUTURE, 2, es.PLURAL)),
       ("ser", u"serán",     (es.FUTURE, 3, es.PLURAL)),
       ("ser", u"sé",        (es.PRESENT, 2, es.SINGULAR, es.IMPERATIVE)),
       ("ser", u"sed",       (es.PRESENT, 2, es.PLURAL, es.IMPERATIVE)),
       ("ser",  u"sea",      (es.PRESENT, 1, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"seas",     (es.PRESENT, 2, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"sea",      (es.PRESENT, 3, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"seamos",   (es.PRESENT, 1, es.PLURAL, es.SUBJUNCTIVE)),
       ("ser",  u"seáis",    (es.PRESENT, 2, es.PLURAL, es.SUBJUNCTIVE)),
       ("ser",  u"sean",     (es.PRESENT, 3, es.PLURAL, es.SUBJUNCTIVE)),
       ("ser",  u"fuera",    (es.PAST, 1, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"fueras",   (es.PAST, 2, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"fuera",    (es.PAST, 3, es.SINGULAR, es.SUBJUNCTIVE)),
       ("ser",  u"fuéramos", (es.PAST, 1, es.PLURAL, es.SUBJUNCTIVE)),
       ("ser",  u"fuerais",  (es.PAST, 2, es.PLURAL, es.SUBJUNCTIVE)),
       ("ser",  u"fueran",   (es.PAST, 3, es.PLURAL, es.SUBJUNCTIVE))):
         self.assertEqual(es.conjugate(v1, tense), v2)
     print "pattern.es.conjugate()"
Ejemplo n.º 18
0
def verbosInfinitivos(cadena):
    t = parsetree(cadena)
    verbos = search('VB*', t)
    print('verbos =', verbos)
    #lis=verbos.match.string
    #print ('list: ',lis)
    #print() #no puedo convertirlo a lista de una?? LAMBDA
    lista = []
    for match in verbos:
        lista.append((match.string, conjugate(match.string, INFINITIVE)))
    #print ('lista for: ',lista)
    #print (lista[3][1])
    return lista
Ejemplo n.º 19
0
def ingresarPalabra(dicPalabras, text):
    """esta funcion verifica si es una palabra valida y cual es su clasificacion, y la agrega al diccionario"""
    try:
        clasificacion = parse(text).split('/')[1][0:2]

        if esPalabraValida(text):
            if (clasificacion == 'VB'):
                enInfinitivo = conjugate(text, INFINITIVE)
                articulo = Wiktionary(language='es').search(enInfinitivo)
            elif (clasificacion == 'JJ'):
                adjetivo = attributive(text, gender=NEUTRAL)
                articulo = Wiktionary(language='es').search(adjetivo)
            elif (clasificacion == 'NN'):
                articulo = Wiktionary(language='es').search(text)
            aux = str(articulo.sections)
            if 'ADJ' in aux.upper() and clasificacion == 'JJ':
                print('La palabra es un adjetivo')
            elif 'VERB' in aux.upper() and clasificacion == 'VB':
                print('La palabra es un verbo')
            elif 'SUST' in aux.upper() and clasificacion == 'NN':
                print('La palabra es un sustantivo')

            if (clasificacion != 'JJ' and clasificacion != 'NN'
                    and clasificacion != 'VB'):
                GenerarReporte('La palabra ' + text + ' no existe en pattern.')

            print('La palabra es valida y es un', articulo.sections[3].title)
            dicPalabras[clasificacion][text] = buscarDefinicion(text)
            print(dicPalabras[clasificacion][text])

            return True
        else:
            if (clasificacion == 'JJ' or clasificacion == 'NN'
                    or clasificacion == 'VB'):
                GenerarReporte(
                    'La palabra ' + text +
                    ' no fue encontrada en Wiktionary, pero sí en pattern siendo un '
                    + clasificacion)
                dicPalabras[clasificacion][text] = sg.PopupGetText(
                    'Definicion: ')
                return True
            else:
                GenerarReporte(
                    'La palabra ' + text +
                    ' no fue encontrada en Wiktionary y tampoco en pattern.')

    except TypeError:
        GenerarReporte('La palabra ' + text + ' no es valida.')
        print('La palabra ingresada no es valida.')

    return False
Ejemplo n.º 20
0
def generar_texto(lista):
    archivo = open("verbos.json", "w")
    diccionario = {}
    for x in lista:
        for y in x:
            if ((y[1] == 'VB') or (y[1]) == 'VBI'):
                verbo = conjugate(y[0], INFINITIVE)
                if not verbo in diccionario:
                    diccionario[verbo] = 0
                diccionario[verbo] = diccionario[verbo] + 1
    lista_verbos = []
    for clave in diccionario:
        lista_verbos.append({clave: diccionario[clave]})
    json.dump(lista_verbos, archivo)
Ejemplo n.º 21
0
def generar_texto(lista):
    archivo = open("verbos.json","w")
    diccionario = {}
    for x in lista:
        for y in x: 
            if ((y[1] == 'VB') or (y[1])=='VBI'): 
                 verbo = conjugate(y[0],INFINITIVE)
                 if not verbo in diccionario:
                     diccionario[verbo] = 0
                 diccionario[verbo] = diccionario[verbo] + 1
    lista_verbos = []
    for clave in diccionario:
        lista_verbos.append({clave:diccionario[clave]})
    json.dump(lista_verbos,archivo)
Ejemplo n.º 22
0
def modifica_linea(dialogo):
    p = parse(dialogo)
    lista = p.split(' ')
    linea = []
    for i in lista:
        palabra = i.split('/')
        if palabra[1] == 'VB':
            p = conjugate(palabra[0], INFINITIVE)
            linea.append(p)
        elif palabra[1] == 'NN':
            linea.append(singularize(palabra[0]))
        else:
            linea.append(palabra[0])
    l = " ".join(linea)
    return l
Ejemplo n.º 23
0
	def tagLemma(self, word_old):
		#print tag(word_old)
		for word, pos in tag(word_old): 
			if pos=="NNS": #plurales
				x = singularize(word)
			elif pos in ["VB","VBG","VBZ","VBP","VBD","VBN","MD"]: # verbos a infinitivo 
				x = conjugate(word, INFINITIVE)
				#To-Do: fix this
				if x: # a veces da error al conjugar
					x = x
				else:
					x = word
			else:
				x = word  
		return x
 def transformar_dialogo(self, dialogo):
     "Transforma un diálogo a uno nuevo con los verbos en infinitivo"
     palabras = parse(dialogo).split()
     nueva_linea = ''
     print(palabras)
     for elem in palabras:
         for elem2 in elem:
             if 'VB' in elem2[1]:
                 pal = elem2[0]
                 pal = str(pal)
                 conj = conjugate(pal, INFINITIVE)
                 nueva_linea = nueva_linea + conj + ' '
             else:
                 pal = str(elem2[0])
                 nueva_linea = nueva_linea + pal + ' '
     return nueva_linea
Ejemplo n.º 25
0
 def unify_tokens(self):
     """
     Singuralizes nouns, conjugates verbs to infinitive and passes adjectives to
     predicative form in tokens
     :return: Tokens
     """
     if self._analysis is None:
         raise Exception('It\'s necessary execute first analize')
     for i in range(len(self._tokens)):
         if self._analysis[i][1][0] == 'n':
             self._tokens[i] = singularize(self._tokens[i])
         elif self._analysis[i][1][0] == 'v':
             self._tokens[i] = conjugate(self._tokens[i], INFINITIVE)
         elif self._analysis[i][1][0] == 'a':
             self._tokens[i] = predicative(self._tokens[i])
     return self._tokens
Ejemplo n.º 26
0
def to_infinitive(word):
    u"""
    Conjugate a verb to its infinitive form.

    >>> to_infinitive(u'aprendas')
    u'aprender'
    >>> to_infinitive(u'enseñar')
    'ensenar'
    >>> to_infinitive('empieza')
    u'empezar'
    >>> to_infinitive(u'acabó')
    u'acabar'
    >>> to_infinitive('fuiste')
    u'ser'
    """
    return conjugate(normalize_word(word))
Ejemplo n.º 27
0
 def unify_tokens(self):
     """
     Singuralizes nouns, conjugates verbs to infinitive and passes adjectives to
     predicative form in tokens
     :return: Tokens
     """
     if self._analysis is None:
         raise Exception('It\'s necessary execute first analize')
     for i in range(len(self._tokens)):
         if self._analysis[i][1][0] == 'n':
             self._tokens[i] = singularize(self._tokens[i])
         elif self._analysis[i][1][0] == 'v':
             self._tokens[i] = conjugate(self._tokens[i], INFINITIVE)
         elif self._analysis[i][1][0] == 'a':
             self._tokens[i] = predicative(self._tokens[i])
     return self._tokens
Ejemplo n.º 28
0
def ingresarPalabra(dicPalabras, text):
    """Verifica que la palabra sea v�lida tanto en Wiktionary como en Pattern.
     la palabra existe, la clasifica en verbo/sustantivo/adjetivo y la agrega a la lista de palabras.
    Caso contrario, genera el reporte con una descripcion del error.
    Retorna verdadero o falso dependiendo si la palabra se inserto correctamente o no."""
    try:
        clasificacion = clasificarPalabra(text)
        
        if esPalabraValida(text):                        
                if (clasificacion == 'VB'):      
                    enInfinitivo = conjugate(text, INFINITIVE)
                    articulo = Wiktionary(language='es').search(enInfinitivo)
                elif (clasificacion == 'JJ'):
                    adjetivo = attributive(text, gender=NEUTRAL)
                    articulo = Wiktionary(language='es').search(adjetivo)
                elif (clasificacion == 'NN'):
                    articulo = Wiktionary(language='es').search(text)
                    
                aux = str(articulo.sections)
                
                if clasificacion == 'JJ' and 'ADJ' in aux.upper():
                    clasificacion = 'JJ'
                elif clasificacion == 'VB' and 'VERB' in aux.upper():
                    clasificacion == 'VB'
                elif clasificacion == 'NN' and 'SUST' in aux.upper():
                    clasificacion == 'NN'
                else:
                    GenerarReporte('La definición de la palabra' + text + ' no coincide en Pattern y Wiktionary, se la clasificó como ' + clasificacion)
                if (clasificacion != 'JJ' and clasificacion != 'NN' and clasificacion != 'VB'):
                    GenerarReporte('La palabra ' + text + ' no existe en pattern.')
                    
                dicPalabras[clasificacion][text] = buscarDefinicion(text)
                return True
        else:
            if (clasificacion == 'JJ' or clasificacion == 'NN' or clasificacion == 'VB'):
                GenerarReporte('La palabra ' + text + ' no fue encontrada en Wiktionary pero si en pattern siendo un ' + clasificacion)
                dicPalabras[clasificacion][text] = sg.PopupGetText('Definición' 'No se ha encontrado la palabra en Wiktionary ni en Pattern. Ingrese una definición para la palabra: ')
                return True
            else:
                GenerarReporte('La palabra ' + text + ' no fue encontrada en Wiktionary y tampoco en pattern.')
                sg.Popup('La palabra ingresada no es válida. Se ha agregado esta situación en un reporte llamado ArchivoReporte.txt en el directorio.')
    except:
            GenerarReporte('La palabra ' + text + ' no es válida.')
            sg.Popup('La palabra ingresada no es válida. Se ha agregado esta situacion en un reporte ArchivoReporte.txt en el directorio.')
        
    
    return False
 def to_conjugate(self, verbo):
     mod = ['INDICATIVE', 'IMPERATIVE', 'CONDITIONAL', 'SUBJUNCTIVE']
     aspec = ['IMPERFECTIVE', 'PERFECTIVE', 'PROGRESSIVE']
     tiempo = ['INFINITIVE', 'PRESENT', 'PAST', 'FUTURE']
     tiempo = tiempo[2]
     PALABRA = verbo
     PERSONA = 3
     cong = conjugate(
         PALABRA,
         tense=tiempo.lower(),  # INFINITIVE, PRESENT, PAST, FUTURE 
         person=PERSONA,  # 1, 2, 3 or None 
         number='SG'.lower(),  # SG, PL 
         mood=mod[0].lower(
         ),  # INDICATIVE, IMPERATIVE, CONDITIONAL, SUBJUNCTIVE 
         aspect=aspec[1].lower(),  # IMPERFECTIVE, PERFECTIVE, PROGRESSIVE 
         negated=False)
     return cong
Ejemplo n.º 30
0
Archivo: ner.py Proyecto: dgcnz/nlp
def syntax_analyze(sent: str) -> Tuple[List, str]:
    parsed_list = []
    command = None
    if sent is not None:
        parsed = parse(sent, lemmata=True)
        parsed_list = parsed.split(" ")
        for s in split(parsed)[0]:
            if s.index == 0 and s.type != "VB":
                flag, fixed = is_imperative(str(s))
                if flag:
                    parsed_list[s.index] = fixed
                    command = fixed.split("/")[-1]
            if s.index == 0 and s.type == "VB":
                if conjugate(
                        str(s), PRESENT, 2, SG,
                        mood=IMPERATIVE) == str(s).lower():
                    command = str(s.lemma)
    if command is None:
        command = "conversar"
    return parsed_list, command
Ejemplo n.º 31
0
def verbosInfinitivos (txt):
	"""Recibe un string. Devuelve una lista de sus verbos en infinitivo."""

	print()
	print('análisis hecho por pattern: ')
	lista_general = parse(txt).split()[0]
	print (lista_general)
	
	lista_verbos = ['VB', 'VBP', 'VBZ', 'VBG', 'VBD', 'VBN']
	verbos = list(filter(lambda verbo: verbo[1] in lista_verbos, lista_general))
	
	print()
	print('los verbos de la oración son: ')
	print(verbos)	
	
	verbos_infinitivo = []
	for v in verbos:
		if v[1] in lista_verbos:
			verbos_infinitivo.append(conjugate(v[0], INFINITIVE))
	print()
	print('los verbos pasados a infinitivo son: ')			
	return verbos_infinitivo
Ejemplo n.º 32
0
import json
from pattern.es import parse, conjugate, INFINITIVE

dic_verbos = {}

with open("archivoEj6Texto.txt","r") as arch:
    for line in arch:
        lista = parse(line).split()
        print(lista)
        for pal in lista:
            print(pal)
            if ('VB' in pal):
                dic_verbos[conjugate(pal,INFINITIVE)] = {}
                dic_verbos[palabra]['cantidad'] += 1

print(dic_verbos)
Ejemplo n.º 33
0
#print (search('JJ', t)) # all adjectives
#print (search('NN', t) )# all nouns
#print (search('NP', t) )# all noun phrases

#parece que no anda con 3.7

s = EJ
#s = limpiar_str(EJ)
#debug(s)
p = parse(s)
#debug(p)
t = parsetree(s)
#debug(t)
verbos = search('VB*', t)
#debug(verbos)
#print verbos[0].string
print
print
print('  Con search: ')
print(v.string, '->', conjugate(v.string, INFINITIVE))
print()
print('  Con chunks: ')
for sentence in t:
    for chunk in sentence.chunks:
        #print (chunk.type, [(w.string, w.type) for w in chunk.words])
        if chunk.type == 'VP':
            for w in chunk.words:
                print(w.string, '->', conjugate(w.string, INFINITIVE))

#print (conjugate('soy', INFINITIVE))
Ejemplo n.º 34
0
import json
import os
from pattern.es import tag
from pattern.es import conjugate
from pattern.es import INFINITIVE

archivo = open(os.path.join("archivos","texto"), "r")
verbos = open(os.path.join("archivos","verbos.json"), "w")
dicc = {}
listaVerbos = []
# Almaceno todos los verbos
for palabra, tipo in tag(archivo.read()):
    if (tipo == 'VB'):
        listaVerbos.append(conjugate(palabra, INFINITIVE))
# Creo el dicc para el json verbo:apariciones
for verbo in set(listaVerbos):
    dicc[verbo] = listaVerbos.count(verbo)
# Preparo la lista para el JSON
listaVerbos = []
for verbo, cantidad in dicc.items():
    listaVerbos.append({verbo: cantidad})
# Escribo el JSON
json.dump(listaVerbos, verbos)
archivo.close()
Ejemplo n.º 35
0
def convertir_verbo(archivo):
    with open(archivo, 'r') as f:
        arch = json.load(f)
        for x in arch:
            palabra = conjugate(x, INFINITIVE)
            lista.append(palabra)
Ejemplo n.º 36
0
from pattern.es import tag
from pattern.es import INFINITIVE
from pattern.es import conjugate
from collections import Counter
frase = "Este es un párrafo de prueba. El verbo ser, será el mas utilizado. El otro será crear, por eso se creó la oración de esta manera. Por último, se creará esta oración que posee el tercer verbo: poseer. Nada más que decir."
lista_verbos = list(
    filter(lambda x: x[1] == 'VB',
           tag(frase)))  # Filtro de la lista solo los que son verbos
lista_verbos = list(map(lambda x: conjugate(x[0], INFINITIVE),
                        lista_verbos))  # Convierto los verbos en infinitivo
print(Counter(lista_verbos).most_common(3))
Ejemplo n.º 37
0
def verb_conjugation():
    print(conjugate('Soy', INFINITIVE))
    print(conjugate('Soy', PAST))
Ejemplo n.º 38
0
import json
from pattern.es import parse, conjugate
from pattern.es import INFINITIVE, PRESENT, PAST, SG, PL, SUBJUNCTIVE, PERFECTIVE, IMPERFECT, PRETERITE

"""Leer un texto desde un archivo y generar uno nuevo (denominado verbos.json) que contenga una estructura con todos los verbos convertidos
a infinitivo junto con la cantidad de apariciones de cada uno"""

with open("p04e03_Datos.txt", "r") as archivo:
    datos = archivo.read().split(', ')

verbos = []

for palabra in datos:
    #print(parse(palabra))
    #print(parse(conjugate(palabra, INFINITIVE)))
    if parse(conjugate(palabra, INFINITIVE)).split('/')[1] == 'VB':
        verbos.append(parse(conjugate(palabra, INFINITIVE)).split('/')[0])
    #print()

#print(verbos)
diccionario = {}
dt_string = 'verbos'
diccionario[dt_string] = verbos

#guardo el diccionario en un archivo json
with open('verbos.json', "w") as archivo_nuevo:
    json.dump(diccionario, archivo_nuevo)