2016-09-08 5 views
0

Я нашел этот код, который лексирует текст.
Этот текст разделен на предложения, а затем обозначен.
И, наконец, маркеры леммматизируются.Лемматизация с использованием StanfordCoreNLP

Моя проблема в том, что мне не нужно делать шаги splitting и tokenize, потому что я уже сделал это в своей программе.
Я просто хочу интегрировать шаг lemmatization в мою программу, так как у меня уже есть список слов, которые я должен лемматизировать.

Вот программа, которую я хочу интегрировать, без шагов, которые происходят до лемматизации.

import java.util.LinkedList; 
import edu.stanford.nlp.ling.CoreAnnotations.LemmaAnnotation; 
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; 
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 textd 
    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)); 

ответ

0

Вы можете просто не разметить вашу строку, и пусть это будет lemmatized в целом.

Если я правильно понял, вам нужно будет удалить эти два действия, которые вы уже сделали из свойств.

tokenize, ssplit, 

Хотя, честно говоря, не помешает им покинуть их, если вы уже выполнили эти шаги. Одну строку нельзя разбить.

Если у вас есть список строк, вы можете перебрать их по отдельности и вызвать метод lemmatize на одном слове так же, как предложение. Примечание. Вы можете легко отредактировать метод, чтобы вернуть только одну строку леммы из списка (или вообще попытаться удалить список из метода).

+0

Нет, это не работает. «tokenize, ssplit, pos» требуются для «леммы» –

+0

@BingRen Читайте вопрос? * Мне не нужно делать шаги разделения и токенизации, потому что я уже сделал это в своей программе * –

+1

Если вы удалите эти два шага, вы получите исключение: java.lang.IllegalArgumentException: аннотатор «pos» требует аннотации " TextAnnotation». Обычные требования к этому комментатору являются: разметить, ssplit \t в edu.stanford.nlp.pipeline.StanfordCoreNLP.construct (StanfordCoreNLP.java:456) \t в edu.stanford.nlp.pipeline.StanfordCoreNLP. (StanfordCoreNLP.java:150) \t at edu.stanford.nlp.pipeline.StanfordCoreNLP. (StanfordCoreNLP.java:146) \t at edu.stanford.nlp.pipeline.StanfordCoreNLP. (StanfordCoreNLP.java:133) –

0

Вам необходимо включить модель языка в свой проект в качестве вашей библиотеки. Файл указан в следующей ссылке: «http://stanfordnlp.github.io/CoreNLP/» для английской модели имя файла «stanford-english-corenlp-models-current.jar». Также доступно для нескольких языков, включая 中国, немецкий, арабский и т. Д.

1

Если вам нужно только лемматизация, тогда лучше использовать простое предложение.

import edu.stanford.nlp.simple.Sentence; 

public List<String> getLemmasList(String text) { 
    Sentence sentence = new Sentence(text); 
    return lemmas = sentence.lemmas(); 
} 

Вы также можете получить слова, part_of_speech от:

sentence.word(i); 
sentence.posTag(i); 
Смежные вопросы