简体   繁体   中英

how to Read data from a text file in java to extract data using StanfordNLP rather than reading text from a simple String

i tried using Annotation document = new Annotation("this is a simple string"); and also tried CoreDocument coreDocument = new CoreDocument(text); stanfordCoreNLP.annotate(coreDocument); but not able to solve it to read from a text file

Use as below (see the example given here ):

// creates a StanfordCoreNLP object, with POS tagging, lemmatization, NER, parsing, and coreference resolution 
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

// read some text from the file..
File inputFile = new File("src/test/resources/sample-content.txt");
String text = Files.asCharSource(inputFile, Charset.forName("UTF-8")).read();

// create an empty Annotation just with the given text
Annotation document = new Annotation(text);

// run all Annotators on this text
pipeline.annotate(document);

// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);

for(CoreMap sentence: sentences) {
  // traversing the words in the current sentence
  // a CoreLabel is a CoreMap with additional token-specific methods
  for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
    // this is the text of the token
    String word = token.get(TextAnnotation.class);
    // this is the POS tag of the token
    String pos = token.get(PartOfSpeechAnnotation.class);
    // this is the NER label of the token
    String ne = token.get(NamedEntityTagAnnotation.class);
    
    System.out.println("word: " + word + " pos: " + pos + " ne:" + ne);
  }

Update

Alternatively, for reading the file contents, you could use the below that uses the built-in packages of Java; thus, no need for external packages. Depending on the characters in your text file, you can choose the appropriate Charset . As described here , " ISO-8859-1 is an all-inclusive charset, in the sense that it is guaranteed not to throw MalformedInputException ". The below uses that Charset .

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

...
        Path path = Paths.get("sample-content.txt");
        String text = "";
        try {
            text = Files.readString(path, StandardCharsets.ISO_8859_1); //StandardCharsets.UTF_8
        } catch (IOException e) {
            e.printStackTrace();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM