the stanford spanish natural language corenlp java nlp

java - natural - stanford nlp spanish



LematizaciĆ³n java (5)

Estoy buscando una implementación de lemmatisation para inglés en Java. Ya encontré algunas, pero necesito algo que no necesite mucha memoria para ejecutar (1 GB arriba). Gracias. No necesito un stemmer.


¡La respuesta de Chris con respecto al Lematizador Standford es genial! Absolutamente hermoso. Incluso incluyó un puntero a los archivos jar, por lo que no tuve que buscarlo en Google.

Pero una de sus líneas de código tenía un error de sintaxis (de alguna manera cambió el final cerrando paréntesis y punto y coma en la línea que comienza con "lemmas.add ...), y olvidó incluir las importaciones.

En cuanto al error NoSuchMethodError, generalmente se debe a que el método no se convierte en estático público, pero si se mira el código en sí (en http://grepcode.com/file/repo1.maven.org/maven2/com.guokr/stan-cn-nlp/0.0.2/edu/stanford/nlp/util/Generics.java?av=h ) ese no es el problema. Sospecho que el problema está en algún lugar de la ruta de compilación (estoy usando Eclipse Kepler, por lo que no fue ningún problema configurar los 33 archivos jar que uso en mi proyecto).

Debajo está mi pequeña corrección del código de Chris, junto con un ejemplo (mis disculpas a Evanescence por haber matado sus letras perfectas):

import java.util.LinkedList; import java.util.List; import java.util.Properties; import edu.stanford.nlp.ling.CoreAnnotations.LemmaAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap; public class StanfordLemmatizer { protected StanfordCoreNLP pipeline; public StanfordLemmatizer() { // Create StanfordCoreNLP object properties, with POS tagging // (required for lemmatization), and lemmatization Properties props; props = new Properties(); props.put("annotators", "tokenize, ssplit, pos, lemma"); /* * This is a pipeline that takes in a string and returns various analyzed linguistic forms. * The String is tokenized via a tokenizer (such as PTBTokenizerAnnotator), * and then other sequence model style annotation can be used to add things like lemmas, * POS tags, and named entities. These are returned as a list of CoreLabels. * Other analysis components build and store parse trees, dependency graphs, etc. * * This class is designed to apply multiple Annotators to an Annotation. * The idea is that you first build up the pipeline by adding Annotators, * and then you take the objects you wish to annotate and pass them in and * get in return a fully annotated object. * * StanfordCoreNLP loads a lot of models, so you probably * only want to do this once per execution */ this.pipeline = new StanfordCoreNLP(props); } public List<String> lemmatize(String documentText) { List<String> lemmas = new LinkedList<String>(); // Create an empty Annotation just with the given text Annotation document = new Annotation(documentText); // run all Annotators on this text this.pipeline.annotate(document); // Iterate over all of the sentences found List<CoreMap> sentences = document.get(SentencesAnnotation.class); for(CoreMap sentence: sentences) { // Iterate over all tokens in a sentence for (CoreLabel token: sentence.get(TokensAnnotation.class)) { // Retrieve and add the lemma for each word into the // list of lemmas lemmas.add(token.get(LemmaAnnotation.class)); } } return lemmas; } public static void main(String[] args) { System.out.println("Starting Stanford Lemmatizer"); String text = "How could you be seeing into my eyes like open doors? /n"+ "You led me down into my core where I''ve became so numb /n"+ "Without a soul my spirit''s sleeping somewhere cold /n"+ "Until you find it there and led it back home /n"+ "You woke me up inside /n"+ "Called my name and saved me from the dark /n"+ "You have bidden my blood and it ran /n"+ "Before I would become undone /n"+ "You saved me from the nothing I''ve almost become /n"+ "You were bringing me to life /n"+ "Now that I knew what I''m without /n"+ "You can''ve just left me /n"+ "You breathed into me and made me real /n"+ "Frozen inside without your touch /n"+ "Without your love, darling /n"+ "Only you are the life among the dead /n"+ "I''ve been living a lie, there''s nothing inside /n"+ "You were bringing me to life."; StanfordLemmatizer slem = new StanfordLemmatizer(); System.out.println(slem.lemmatize(text)); } }

Aquí están mis resultados (quedé muy impresionado, captó "''s" como "es" (a veces), e hizo casi todo lo demás perfectamente):

Iniciando Stanford Lemmatizer

Agregar tokenize de annotator

Agregar ssplit de anotador

Añadiendo annotator pos

Leer el modelo de etiquetador de POS de edu / stanford / nlp / models / pos-tagger / english-left3words / english-left3words-distsim.tagger ... hecho [1.7 sec].

Añadiendo el lema del anotador

[cómo, podría, usted, ser, ver, en, mi, ojo, como, abrir, puerta,?, usted, conducir, yo, abajo, en, mi, núcleo, donde, yo, tener, convertirse, así, entumecer , sin, a, alma, mi, espíritu, es, dormir, en algún lugar, frío, hasta, usted, encontrarlo, allí, y, llevarlo, atrás, a casa, usted, despertar, yo, arriba, adentro, llamar, mi, nombre, y, guardar, yo, de, el, oscuro, usted, tener, pujar, mi, sangre, y, ello, correr, antes, yo, sería, convertirme, deshacer, usted, guardar, yo, de, el, nada, yo, tengo, casi, conviértete, tú, sé, trae, yo, a, vida, ahora, eso, yo, sé, qué, yo, sé, sin, tú, puedes, tengo, solo, vete, yo, tú, respira, entra, yo, y, hago, yo, real, congelado, adentro, sin, tú, toca, sin, tú, amor, ,, cariño, solo, tú, sé, el, vida, entre, el, muerto, yo, tengo, ser, vivir, a, mentir, ,, allí, ser, nada, adentro, tú, ser, traer, yo, a, vida,.]




La biblioteca de Stanford CoreNLP Java contiene un lemmatizador que requiere un poco de recursos, pero lo he ejecutado en mi computadora portátil con <512 MB de RAM.

Para usarlo:

  1. Descargue los archivos jar ;
  2. Cree un nuevo proyecto en su editor de elección / haga una secuencia de comandos ant que incluya todos los archivos jar contenidos en el archivo que acaba de descargar;
  3. Cree una nueva Java como se muestra a continuación (basada en el fragmento del sitio de Stanford);

import java.util.Properties; public class StanfordLemmatizer { protected StanfordCoreNLP pipeline; public StanfordLemmatizer() { // Create StanfordCoreNLP object properties, with POS tagging // (required for lemmatization), and lemmatization Properties props; props = new Properties(); props.put("annotators", "tokenize, ssplit, pos, lemma"); // StanfordCoreNLP loads a lot of models, so you probably // only want to do this once per execution this.pipeline = new StanfordCoreNLP(props); } public List<String> lemmatize(String documentText) { List<String> lemmas = new LinkedList<String>(); // create an empty Annotation just with the given text Annotation document = new Annotation(documentText); // run all Annotators on this text this.pipeline.annotate(document); // Iterate over all of the sentences found List<CoreMap> sentences = document.get(SentencesAnnotation.class); for(CoreMap sentence: sentences) { // Iterate over all tokens in a sentence for (CoreLabel token: sentence.get(TokensAnnotation.class)) { // Retrieve and add the lemma for each word into the list of lemmas lemmas.add(token.get(LemmaAnnotation.class)); } } return lemmas; } }


Puede probar la API Lemmatizer gratuita aquí: http://twinword.com/lemmatizer.php

Desplácese hacia abajo para encontrar el punto final Lemmatizer.

Esto le permitirá obtener "perros" para "perro", "habilidades" para "habilidad".

Si pasa un parámetro POST o GET llamado "texto" con una cadena como "plantas caminó":

// These code snippets use an open-source library. http://unirest.io/java HttpResponse<JsonNode> response = Unirest.post("[ENDPOINT URL]") .header("X-Mashape-Key", "[API KEY]") .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .field("text", "walked plants") .asJson();

Obtienes una respuesta como esta:

{ "lemma": { "plant": 1, "walk": 1 }, "result_code": "200", "result_msg": "Success" }