Подтвердить что ты не робот

Лемматизация java

Я ищу lemmatisation для английского языка на Java. Я нашел несколько уже, но мне нужно что-то, что не нужно много памяти для запуска (1 ГБ). Благодарю. Мне не нужен стример.

4b9b3361

Ответ 1

Stanford CoreNLP Библиотека Java содержит lemmatizer, который немного ресурсоемкий, но я запустил его на своем ноутбуке с 512 МБ ОЗУ.

Чтобы использовать его:

  • Загрузите файлы jar;
  • Создайте новый проект в своем выбранном редакторе/создайте ant script, который включает все файлы jar, содержащиеся в загруженном вами архиве;
  • Создайте новую Java, как показано ниже (на основе фрагмента из сайта 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;
    }
}

Ответ 2

Ответ Криса относительно Standford Lemmatizer замечательный! Абсолютно красивый. Он даже включил указатель на файлы jar, поэтому мне не пришлось его искать.

Но одна из его строк кода имела синтаксическую ошибку (он как-то переключил конечные закрывающие круглые скобки и точку с запятой в строку, начинающуюся с "lemmas.add...), и он забыл включить импорт.

Что касается ошибки NoSuchMethodError, это обычно вызвано тем, что этот метод не становится общедоступным, но если вы посмотрите на сам код (http://grepcode.com/file/repo1.maven.org/maven2/com.guokr/stan-cn-nlp/0.0.2/edu/stanford/nlp/util/Generics.java?av=h), это не проблема. Я подозреваю, что проблема находится где-то в пути сборки (я использую Eclipse Kepler, поэтому не было проблем с настройкой 33 файлов jar, которые я использую в своем проекте).

Ниже приводится моя небольшая коррекция кода Криса, а также пример (мои извинения за Evanescence за то, что они уничтожили их прекрасную лирику):

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 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 nothing inside \n"+
                "You were bringing me to life.";
        StanfordLemmatizer slem = new StanfordLemmatizer();
        System.out.println(slem.lemmatize(text));
    }

}

Вот мои результаты (я был очень впечатлен, он попадал "в" как "есть" (иногда) и делал почти все остальное отлично):

Запуск Лемматизатора Стэнфорда

Добавление аннотатора tokenize

Добавление аннотатора ssplit

Добавление аннотатора pos

Чтение модели тегов POS из edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger... сделано [1,7 сек].

Добавление леммы-аннотатора

[как, может, вы, смотрите, в, мой, глаз, как, открывайте, дверь, вы, возглавляете, я, вниз, в, мое, ядро, где, я, так, онемение, без, а, душа, мой, дух, сон, где-то, холодный, пока ты не найдешь, не найдешь, не найдешь, не вернешься, не вернешься домой, ты, проснись, я, внутри, зов, мой, имя и, кроме того, я, из, темный, ты, имеешь, предлагаешь, мой, кровь, и, он, беги, прежде, я, бы, стал, отменил, ты, спаси, Я, от, ничего, я, почти, стал, ты, будешь, приносите, я, к, жизнь, теперь, я, знаю, что, я, будь, без, вы, можете, просто, уходи, я, ты, дыши, в, я, и, делаю, я, реальный, замороженный, внутри, без тебя, прикосновения, без, ты, любовь, милый, только ты, жизнь, среди, мертвых, я, есть, быть, жить, а, ложь, там, быть, ничего, внутри, вы, быть, приносить, я, в, жизнь.]

Ответ 3

Существует JNI для hunspell, который используется для проверки в открытом офисе и FireFox. http://hunspell.sourceforge.net/

Ответ 4

Вы можете попробовать бесплатный API Lemmatizer здесь: http://twinword.com/lemmatizer.php

Прокрутите вниз, чтобы найти конечную точку Lemmatizer.

Это позволит вам получить "собак" для "собак", "способностей" к "способностям".

Если вы передадите параметр POST или GET под названием "текст" со строкой, подобной "шагающим растениям":

// 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();

Вы получите ответ вроде этого:

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