예제 #1
0
def verificar_palabra(palabra, dic):
    claves = {'NN': 'sustantivo', 'JJ': 'adjetivo', 'VB': 'verbo'}
    try:
        article = engine.search(palabra)
        eti = article.sections[3].title.lower().split(' ')[0]
        print(eti)
        dic[eti].append(palabra)
        dic['lista'].append(palabra)
        dic['def'].update({palabra: article.sections[3].content})
        if ((claves[parse(palabra).split()[0][0][1]] != eti)):
            dic['reporte'].append(
                'La palabra {} no coincide con pattern.es'.format(palabra))
    except AttributeError:
        if (parse(palabra).split()[0][0][1] in dic):
            text = sg.PopupGetText('Definición local', '')
            dic['def'].update({palabra: text})
            dic['reporte'].append(
                'La palabra {} no coincide con Wiktionary\n Se utilizará una definición guardada en un archivo local'
                .format(palabra))
            sg.Popup(
                'ADVERTENCIA!',
                'Se utilizará una definición guardada en un archivo local')
        else:
            dic['reporte'].append(
                'No se encuentra la palabra {} en ningun recurso'.format(
                    palabra))
    except KeyError:
        sg.Popup('ADVERTENCIA!',
                 'No esta ingresando ningun sustantivo, adjetivo o verbo')
        dic['reporte'].append(
            'La palabra {} no es ningun sustantivo, adjetivo o verbo'.format(
                palabra))
    return dic
예제 #2
0
def verbosOAdjetivos(palabra, soloVerbosOadjetivos):
    """verifico que sea adjetivo o verbo"""
    #print(palabra)
    dato = parse(palabra)
    VD = parse(palabra).split()[0][0][1]

    #print(VD)
    #print(dato)
    if VD in soloVerbosOadjetivos:
        print(palabra)
        return True
    else:
        return False
예제 #3
0
def buscar_combinacion(vector_compu,valores_letras,tipo_de_palabras):
    '''Función que retorna la 1er palabra que logro armar la computadora con
    las posiciones de las letras usadas'''
    letras=[]
    tipos=[]
    if tipo_de_palabras=="Verbos y Adjetivos":
        tipos=["VB","JJ"]
    elif tipo_de_palabras=="Verbos":
        tipos=["VB"]
    elif tipo_de_palabras=="Adjetivos":
        tipos=["JJ"]
    for i in range(0,len(vector_compu)):
        letras.append(valores_letras[vector_compu[i]].upper())
    palabra=""
    posiciones=[]
    conjuntos=set()
    for i in range(2,len(letras)+1):
        permutaciones=list(itertools.permutations(letras,i))
        for j in permutaciones:
            conjuntos.add(j)
    for i in conjuntos:
        aux="".join(i)
        if ("Ñ" in aux and aux.lower() in es.lexicon.keys())or(aux.lower() in es.lexicon.keys() and aux.lower() in es.spelling.keys()):
            tipo_palabra=es.parse(aux).split("/")[1]
            if tipo_palabra in tipos or len(tipos)==0:
                palabra=aux
                conjunto=i
                break
    if palabra!="":
        for i in conjunto:
            posicion=letras.index(i)
            posiciones.append(posicion)
            letras[posicion]="0"
    return(palabra,posiciones)
예제 #4
0
def es_palabra(nivel, palabras_validas, palabra):
    """
    Función que verifica que la palabra sea válida correspondiente al nivel de la partida.

    Parámetros:
        - nivel (str): nivel de la partida ("fácil", "medio", "difícil").
        - palabras_validas (str): indica el tipo de palabras válidas.
        - palabra (str): palabra a verificar.

    Retorna:
        - (bool): indica si la palabra es válida.
    """

    palabra = palabra.lower()

    if not (palabra in verbs or (palabra in spelling and palabra in lexicon)):

        return False

    tipo = parse(palabra, chunks=False).split("/")[1]

    if nivel == "fácil":

        return tipo.find("NN") != -1 or tipo.find("VB") != -1 or tipo.find(
            "JJ") != -1

    elif nivel == "medio":

        return tipo.find("JJ") != -1 or tipo.find("VB") != -1

    elif nivel == "difícil":
        tipo_valido = "JJ" if palabras_validas == "Adjetivos" else "VB"

        return tipo.find(tipo_valido) != -1
예제 #5
0
    def categoria_gramatical_texto_pattern(self,texto):
            '''
              Grammatical category of each word

              ej. she:PRP drove:VBD a:DT silver:NN pt:NN cruiser:NN
                    PRP: Possesive pronoun
                    VBD: Verb in past tense
                    DT: Determiner
                    NN: Noun in singular
              In:
                    (texto, text) string text               
              Out:
                    (listaCategoria, list) list with grammatical categories associated to every word
            '''
            try:
                    categorias = parse(texto)
                    listaCategoria = []
                    if isinstance(texto, str):
                        texto = unicode(texto, "utf-8", "xmlcharrefreplace")
                    for x in categorias.split():
                        for y in x:
                            listaCategoria.append(y[0]+":"+y[1])
                    return listaCategoria
            except TypeError:
                    return []
            except UnicodeDecodeError:
                    return []
            except:
                    return []    
예제 #6
0
 def check_category_pattern(self, token, index):
     """
     Detects the word's category using Pattern library (when pattern
     library does't know the word it says that the word is a noun).
     :param token: Word to check category
     :param index: Word's index in tokens
     :return category: Word's grammar category
     """
     category = parse(token)
     if '/NN' in category:
         category = 'n'
     elif '/VB' in category:
         category = 'v'
     elif '/JJ' in category:
         category = 'a'
     elif '/CC' or '/CS' in category:
         category = 'c'
     elif '/P' in category:
         category = 'p'
     else:
         category = '-'
     if index >= len(self._analysis):
         self._analysis.append([token, category.ljust(7, '0')])
     else:
         self._tokens[index] = token
         self._analysis[index] = [token, category.ljust(7, '0')]
     return category
예제 #7
0
 def check_category_pattern(self, token, index):
     """
     Detects the word's category using Pattern library (when pattern
     library does't know the word it says that the word is a noun).
     :param token: Word to check category
     :param index: Word's index in tokens
     :return category: Word's grammar category
     """
     category = parse(token)
     if '/NN' in category:
         category = 'n'
     elif '/VB' in category:
         category = 'v'
     elif '/JJ' in category:
         category = 'a'
     elif '/CC' or '/CS' in category:
         category = 'c'
     elif '/P' in category:
         category = 'p'
     else:
         category = '-'
     if index >= len(self._analysis):
         self._analysis.append([token, category.ljust(7, '0')])
     else:
         self._tokens[index] = token
         self._analysis[index] = [token, category.ljust(7, '0')]
     return category
예제 #8
0
 def get_tipo(self):
     """ Verifica su tipo (adj, sus, verb) consuntando
         con Pattern
     """
     parsed = parse(self.nombre)
     parsed = parsed.split('/')
     return parsed[1]
예제 #9
0
    def pos_tagging(self, s):
            '''
              Grammatical category of each word

              ej. she:PRP drove:VBD a:DT silver:NN pt:NN cruiser:NN
                    PRP: Possesive pronoun
                    VBD: Verb in past tense
                    DT: Determiner
                    NN: Noun in singular
              In:
                    (s:string) string text               
              Out:
                    (list) list with grammatical categories associated to every word 
                    in the form 'word:POS'
            '''
            if isinstance(s, str):
                s = unicode(s, "utf-8", "xmlcharrefreplace")
            categories = parse(s)
            list = []
            if isinstance(s, str):
                s = unicode(s, "utf-8", "xmlcharrefreplace")
            for x in categories.split():
                for y in x:
                    list.append(y[0]+":"+y[1])
            return list
예제 #10
0
def segunPattern(palabra, tipo):

    tipo = tipo.lower()
    tipo = tipo.capitalize()

    #Tipo de palabras segun Pattern
    clasifSustantivos = ['NN', 'NNS', 'NNP', 'NNPS']
    clasifAdjetivos = ['JJ', 'JJR', 'JJS']
    clasifVerbos = ['MD', 'VB', 'VBZ', 'VBP', 'VBD', 'VBN', 'VBG']

    #con el .parse obtengo una lista con propiedades de la palabra y me guardo el tipo (propiedades[1])
    propiedades = pattes.parse(palabra)
    propiedades = propiedades.split('/')
    clasificacion = propiedades[1]

    #pregunto si coincide
    resultado = ''
    if (clasificacion in clasifSustantivos):
        resultado = 'Sustantivo'
    elif (clasificacion in clasifAdjetivos):
        resultado = 'Adjetivo'
    elif (clasificacion in clasifVerbos):
        resultado = 'Verbo'

    if (resultado == tipo):
        return True
    else:
        return False
예제 #11
0
def check_jugador(palabra):
    """ recibe una palabra y verifica que sea un verbo, adjetivo o sustantivo,
    retorna True si es asi, o Fale en caso contrario"""
    if len(palabra) >= 2:

        global TIPO
        posibles = posibles_palabras(palabra)
        ok = False
        cont = 0
        #en cuanto encunetre una opcion que de 'True' dejara de comprobar e insertara esa
        while not ok and cont < len(posibles):
            pal = ''
            if es_palabra(posibles[cont]):
                pal = pes.parse(posibles[cont]).split('/')

                if pal[1] in TIPO['adj']:
                    ok = True
                elif pal[1] in TIPO['sus']:
                    ok = True
                elif pal[1] in TIPO['verb']:
                    ok = True
                else:
                    ok = False
            else:

                ok = False


#            print("se chequeo {} el contador es {} y ok esta en {}".format(pal,cont,ok))
            cont += 1
    else:
        return False
    return ok
예제 #12
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
예제 #13
0
 def categoria_gramatical_lista_pattern(self,lista):
         if  isinstance(lista, list):
                 if (all(type(x) is str for x in lista)):
                       try:
                               remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
                               lista=[unicode(s,codificacion) for s in lista]
                               lista=[s.translate(remove_punctuation_map).lower() for s in lista]
                               lista=[str(self.elimina_tildes(s)) for s in lista]
                               lista= filter(None,lista)
                               lista= filter(str.strip, lista)    
                               textoLimpio=" ".join(lista) 
                               categorias =parse(textoLimpio)
                               listaCategoria=[]
                               for x in categorias.split():
                                     for y in x:
                                          listaCategoria.append(y[0].encode('ascii','ignore')+":"+y[1].encode('ascii','ignore'))
                               return listaCategoria
                       except TypeError:
                            return []
                       except UnicodeDecodeError:
                            return []      
                       except:
                            return []
                 else:
                        return []  
         else:
                 return []
예제 #14
0
파일: test_es.py 프로젝트: pawkul/pattern
 def test_parse(self):
     # Assert parsed output with Penn Treebank II tags (slash-formatted).
     # "el gato negro" is a noun phrase, "en la alfombra" is a prepositional noun phrase.
     v = es.parser.parse(u"El gato negro se sentó en la alfombra.")
     self.assertEqual(
         v,  # XXX - shouldn't "se" be part of the verb phrase?
         u"El/DT/B-NP/O gato/NN/I-NP/O negro/JJ/I-NP/O "
         + u"se/PRP/B-NP/O sentó/VB/B-VP/O "
         + u"en/IN/B-PP/B-PNP la/DT/B-NP/I-PNP alfombra/NN/I-NP/I-PNP ././O/O",
     )
     # Assert the accuracy of the Spanish tagger.
     i, n = 0, 0
     for sentence in open(os.path.join(PATH, "corpora", "tagged-es-wikicorpus.txt")).readlines():
         sentence = sentence.decode("utf-8").strip()
         s1 = [w.split("/") for w in sentence.split(" ")]
         s2 = [[w for w, pos in s1]]
         s2 = es.parse(s2, tokenize=False, tagset=es.PAROLE)
         s2 = [w.split("/") for w in s2.split(" ")]
         for j in range(len(s1)):
             if s1[j][1] == s2[j][1]:
                 i += 1
             n += 1
     # print float(i) / n
     self.assertTrue(float(i) / n > 0.92)
     print "pattern.es.parser.parse()"
예제 #15
0
def finalizar_jugada(window, parametros, tablero, palabra, puntos_jugada,
                     jugador, texto):
    """
    Función que brinda información sobre la palabra formada y suma el puntaje de la jugada.

    Parámetros:
        - window (sg.Window): ventana del tablero.
        - parametros (dict): diccionario con párametros que controlan la lógica del juego.
        - tablero (dict): diccionario con la información del tablero.
        - palabra (str): palabra formada en la jugada.
        - puntos_jugada (int): puntos de la jugada.
        - jugador (Jugador): instancia de la clase Jugador que representa al usuario o la computadora.
        - texto (str): indica quien realizó la jugada.
    """

    tipo = parse(palabra.lower(), chunks=False).split("/")[1]
    tipo_palabra = "sustantivo" if tipo.find("NN") != -1 else (
        "verbo" if tipo.find("VB") != -1 else "adjetivo")
    parametros[
        "historial"] += f'\n\n - {texto} formó la palabara "{palabra}" ({tipo_palabra}) y sumó {puntos_jugada} puntos.'
    window["historial"].Update(parametros["historial"])
    jugador.puntaje += puntos_jugada
    tablero["primer_jugada"] = False
    actualizar_tabla(tablero["jugador"], tablero["computadora"], window)
    tablero["palabras_ingresadas"] += [[
        palabra,
        tipo_palabra.capitalize(), puntos_jugada, jugador.nick
    ]]
예제 #16
0
 def test_parse(self):
     # Assert parsed output with Penn Treebank II tags (slash-formatted).
     # "el gato negro" is a noun phrase, "en la alfombra" is a prepositional noun phrase.
     v = es.parser.parse(u"El gato negro se sentó en la alfombra.")
     self.assertEqual(v, # XXX - shouldn't "se" be part of the verb phrase?
         u"El/DT/B-NP/O gato/NN/I-NP/O negro/JJ/I-NP/O " + \
         u"se/PRP/B-NP/O sentó/VB/B-VP/O " + \
         u"en/IN/B-PP/B-PNP la/DT/B-NP/I-PNP alfombra/NN/I-NP/I-PNP ././O/O"
     )
     # Assert the accuracy of the Spanish tagger.
     i, n = 0, 0
     for sentence in open(
             os.path.join(PATH, "corpora",
                          "tagged-es-wikicorpus.txt")).readlines():
         sentence = sentence.decode("utf-8").strip()
         s1 = [w.split("/") for w in sentence.split(" ")]
         s2 = [[w for w, pos in s1]]
         s2 = es.parse(s2, tokenize=False, tagset=es.PAROLE)
         s2 = [w.split("/") for w in s2.split(" ")]
         for j in range(len(s1)):
             if s1[j][1] == s2[j][1]:
                 i += 1
             n += 1
     #print(float(i) / n)
     self.assertTrue(float(i) / n > 0.92)
     print("pattern.es.parser.parse()")
예제 #17
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
예제 #18
0
파일: ner.py 프로젝트: dgcnz/nlp
def is_imperative(word: str):
    base = ENCLITIC_PAT.match(word)
    if base:
        txt = base.group()
        txt = normalize(txt)
        ans = parse(txt, lemmata=True).split('/')
        return True, '/'.join([word] + ans[1:])
    return False, None
예제 #19
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
예제 #20
0
def check_jugador(palabra, preferencias):
    '''
    Recibe una palabra y verifica que sea un verbo, adjetivo o sustantivo,
    retorna True si es asi, o False en caso contrario.
    Este módulo asignará por defecto la dificultad en FÁCIL si no es indicada
    '''
    
    dificultad = preferencias.getNivel()
    if len(palabra) >= 2:
        global TIPO
        posibles = posibles_palabras(palabra)
        ok = False
        cont = 0
        #en cuanto encuentre una opcion que de 'True' dejara de comprobar e insertará esa
        while (not ok) and (cont < len(posibles)):
            pal = ''
            #La condición debe mantener este orden porque, de otro modo, es_palabra podría ejecutarse
            #en el nivel incorrecto. Si el nivel es difícil, es_palabra imprimirá la misma información 3 veces
            if (dificultad == 'facil') and es_palabra(posibles[cont]):
                pal = pes.parse(posibles[cont]).split('/')
                if pal[1] in TIPO['adj']:
                    ok =True
                elif pal[1] in TIPO['sus']:
                    ok= True
                elif pal[1] in TIPO['verb']:
                   ok= True
            elif (dificultad == 'medio' or  dificultad == 'dificil') and es_palabra(posibles[cont]):
                pal = pes.parse(posibles[cont]).split('/')
                if pal[1] in TIPO['adj']:
                    ok =True
                elif pal[1] in TIPO['verb']:
                   ok= True
            elif (dificultad == 'personalizado') and es_palabra(posibles[cont]):
                pal = pes.parse(posibles[cont]).split('/')
                for tipo_palabra in preferencias.getCategoriasPersonalizadas():
                    if pal[1] in TIPO[tipo_palabra]:
                        ok =True
                        break
            else:
                ok = False
#            print("se chequeo {} el contador es {} y ok esta en {}".format(pal,cont,ok))
            cont += 1
    else:
        return False
    return ok
예제 #21
0
def clasificar(palabra):
	"""Esta función analiza la palabra que recibe como patametro. 
	Devuelve True si es sustantivo, verbo o adjetivo. Sino devuelve False. """
	pal = parse(palabra).split()
	if pal[0][0][1] in validas:
		devuelve =  True
	else:
		devuelve = False
	return devuelve
예제 #22
0
def getPoint(sentence, dictionary=spanish):
    wi = []
    p_v = []
    p_a = []
    mu_a = []
    mu_v = []
    v_final = 0
    a_final = 0
    inv_exist = False
    sentence = split(parse(sentence))[0]
    for word in sentence:
        exist, word_str = similar_if_necesary(word.string, dictionary)
        if word.pos == 'RB':
            inv_exist = inv_exist or similar_if_necesary(
                word.string, not_adverbs)[0]

        if exist:
            res = dictionary.get(word_str)
            a = [res['avg'][1], res['std'][1]]
            v = [res['avg'][0], res['std'][0]]

            if (a[0] > 4.5 and a[0] < 5.5) and (
                    v[0] > 4.5
                    and v[0] < 5.88):  # Palabras neutrales con menos peso
                n_rb = -1
            else:
                n_rb = 1

            noun_exist = similar_if_necesary(word.string, nouns)[0]
            if word.pos == 'JJ' or noun_exist:
                quantities = [
                    PosNeg_adverbs.get(x.string, 0) for x in word.chunk.words
                    if x.tag == 'RB'
                ]
                if np.sum(np.abs(quantities)) > 0:
                    sign = np.product(quantities / np.abs(quantities))
                else:
                    sign = 1
                n_rb = sign * (2 + np.sum(np.abs(quantities)))
            wi.append(float(n_rb))
            p_v.append(getProbability(v[1]))
            p_a.append(getProbability(a[1]))
            mu_v.append(v[0])
            mu_a.append(a[0])
    if len(wi) > 0:
        if np.min(
                wi
        ) < 0:  # Esto hace los negativos con menor peso versus los w = 1
            wi = wi + abs(np.min(wi)) + 1

        alpha1 = p_v / np.sum(p_v)  # Solo tiene en cuenta desviacion
        alpha2 = np.multiply(wi, p_v) / np.sum(np.multiply(wi, p_v))
        alpha3 = (wi + np.transpose(p_v)) / np.sum(wi + p_v)
        v_final = np.sum(alpha2 * mu_v)
        a_final = np.sum(alpha2 * mu_a)
    return (v_final, a_final), inv_exist
def analizarPalabra(palabra):
    # pattern analiza la palabra (devuelve lista de lista de lista)
    pal = parse(palabra).split()
    if pal[0][0][1] == 'VB' or pal[0][0][1] == 'JJ':
        # si la palabra es verbo o adjetivo entra al if
        devuelve = 1
    else:
        #La palabra no es válida
        devuelve = 0
    return devuelve
예제 #24
0
def confirmar_Palabra(pal, DIFICULTAD):
    pal = pal.lower()
    p = parse(pal).split()
    if es_Palabra(p[0][0][0]):
        if tipo_Palabra(
                p[0][0][1], DIFICULTAD
        ):  # Si la palabra existe y cumple con su condicion dependiendo su dificultad sigue el juego
            return True
    else:
        return False
예제 #25
0
def grammatical_tagging():
    sentence = "El perro negro muerde sin parar."
    print(tag(sentence))
    pprint(parse(sentence))


#pluralize_singularize()
#verb_conjugation()
#adjetives()
#grammatical_tagging()
예제 #26
0
파일: utils.py 프로젝트: krukmat/smartnews
def only_nouns(sentence):
    new_sentence = []
    structure = parse(sentence).split()
    if structure:
        words = structure[0]
        for token in words:
            if token[0] not in settings.STOP_WORDS and \
                            token[1] in [u'NN', u'NNS', u'NNP',
                                         u'NNPS']:
                new_sentence.append(token[0].lower())
    return new_sentence
예제 #27
0
def pattern(palabra):
    """ Busca en pattern.es si existe la palabra ingresada y de que tipo es, como  cuando la palabra ingresada no existe
        devuelve NN, es decir, que la palabra es un sustantivo, por defecto el tipo es Sustantivo.
        Si al ingresar la palabra esta no estuviese en wiktionary y pattern devolviese NN, esta no será guardada """
    tipo = 'Sustantivo'
    tipo_pattern = parse(palabra)
    if 'VB' in tipo_pattern:
        tipo = 'Verbo'
    elif 'JJ' in tipo_pattern:
        tipo = 'Adjetivo'
    return tipo
예제 #28
0
def pword(text):
    ind = parse(text).split('/')[1][0]

    # verbo
    if ind == 'V':
        word = lemma(text)

    # sustantivo o adjetivo
    else:
        word = singularize(text)
    return word
예제 #29
0
def confirmarPalabra1(letrasTurno):
    palabraTurno = []
    for i in range(len(letrasTurno)):
        x = letrasTurno[i][0]
        y = letrasTurno[i][1]
        palabraTurno.append(TableroLetras[x][y].getLetra())
    palabra = ''.join(palabraTurno)
    if (parse(palabra, tokenize=True, tags=True, chunks=False) == '/NN'):
        return True
    else:
        return False
예제 #30
0
def analizarPalabra(palabra):
    #pattern analiza la palabra (devuelve lista de lista de lista)
    pal = parse(palabra).split()
    #control
    #print('ESTO TENGOOOOOOOOO ' ,pal)
    if pal[0][0][1] == 'VB' or pal[0][0][1] == 'NN' or pal[0][0][
            1] == 'NNS' or pal[0][0][1] == 'JJ':
        #si la palabra es sustantivo, verbo o adjetivo entra al if
        print("La palabra ", pal[0][0][0], " es válida")
    else:
        print("La palabra no es válida")
예제 #31
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
예제 #32
0
def get_pos_tags(string):
    """
    Parse a string and returns its POS (Part Of Speech) tags.

    :see: http://www.clips.ua.ac.be/pages/mbsp-tags for further tag information.

    Example
    >>> get_pos_tags('hola esto es una frase')  # doctest: +ELLIPSIS
    [[u'hola', u'UH'], [u'esto', u'DT'], [u'es', u'VB'], ..., [u'frase', u'NN']]
    """
    return map(lambda tokens: tokens[:2],
               map(lambda s: s.split('/'),
                   parse(string).split(' ')))
예제 #33
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
예제 #34
0
def BuscadorPAT(palabra):
    '''Busca la clasificacion de la palabra en Pattern'''
    s = parse(palabra, relations=True, lemmata=True).split("/")[1]
    tipopattern = '9999'
    if s == 'VB':
        tipopattern = 'verbo'
    elif s == 'JJ':
        tipopattern = 'adjetivo'
    elif s == 'NN':
        tipopattern = 'sustantivo'
    else:
        sg.Popup('No encontrada en pattern')

    return tipopattern
예제 #35
0
def feature_extraction(pd_df):
    all_lemmas, all_tokens = [], []
    for row in pd_df:
        lemmas, tokens = '', ''
        parsed = parse(row, lemmata=True)
        for token in parsed.split():
            for item in token:
                lemmas += item[-1]+' '
                tokens += item[0]+' '
        all_lemmas.append(lemmas)
        all_tokens.append(tokens)
    # create data frame with features
    return pd.DataFrame(data = {"lemmas":all_lemmas,
                                "tokens":all_tokens})
예제 #36
0
def lemmatize_comment(comment):
    #Lemmatizing the comment to generalize words
    lemmatized_comment = ""
    parsed_comment = parse(comment,
                           tokenize=False,
                           tags=False,
                           relations=False,
                           chunks=False,
                           lemmata=True,
                           tagset=None)
    for sentence in parsed_comment.split():
        for token, tag, lemma in sentence:
            lemmatized_comment += lemma + " "
    return lemmatized_comment
예제 #37
0
def preprocessing(doc_set):
    print("Iniciando preprocesamiento...")
    tokenizer = RegexpTokenizer(r'\w+')

    es_stop = get_stop_words('es')
    es_stop.append(u'rt')
    es_stop.append(u'RT')
    es_stop.append(u'Rt')

    normEsp = Cucco(language='es')
    norms = [
        'remove_stop_words', 'replace_punctuation', 'remove_extra_whitespaces',
        'remove_accent_marks'
    ]

    stemmer = SnowballStemmer('spanish')
    #stemmer = Stemmer.Stemmer('spanish')

    out_set = []

    for doc in doc_set:
        doc = normEsp.normalize(doc, norms)
        raw = doc.lower()
        tokens = tokenizer.tokenize(raw)

        stooped_tokens = [i for i in tokens if not i in es_stop]

        #stemmer_words = stemmer.stemWords(stooped_tokens)

        stemmer_words = [parse(s, lemmata=True) for s in stooped_tokens]

        stemmer_words = [a[4] for a in [b.split("/") for b in stemmer_words]]

        #stemmer_words = []
        #for word in stooped_tokens:
        #	#stemmer_words.append(stemmer.stem(word))
        #	stemmer_words.append(word)

        out_set.append(stemmer_words)

    dictionary = corpora.Dictionary(
        out_set)  #diccionario con las palabras enlazadas a una id
    corpus = [dictionary.doc2bow(doc) for doc in out_set]
    #print(corpus[0]) #imprime la bolsa de palabras, son tuplas de la forma (termID, termfrecuency) en el documento 0
    #print(corpus[1])

    print("Done")

    return dictionary, corpus, out_set
예제 #38
0
def clasifico(palabra, tipoPalabra):
    '''
    Función que recibe una palabra y verifica que sea adjetivo o verbo

    Parametros:
    palabra -- es un string
    tipoPalabra -- lista con los tag de los tipos de palabras validas.

    Retorna
    True si está dentro de la clasificación, False caso contrario
    '''
    dato = parse(palabra, tokenize=True, tags=True,
                 chunks=False).replace(palabra, '')
    if (dato in tipoPalabra):
        return True
예제 #39
0
# coding=utf8
from pattern.es import parse
import sys
import codecs

sentence = sys.argv[1]

s = parse(sentence)

print(codecs.encode(s,'utf8'))





예제 #40
0
def leer_texto():
    archivo = open("archivoTexto.txt","r")
    string = archivo.read()
    lista = parse(string).split() 
    return lista