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
Asked
Active
Viewed 178 times
1 Answers
0
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();
}

Chris
- 18,724
- 6
- 46
- 80
-
thank you so much for your answer but java: cannot find symbol symbol: method asCharSource(java.io.File,java.nio.charset.Charset) location: class java.nio.file.Files i am getting this error No candidates found for method call Files.asCharSource(dir, StandardCharsets.UTF_8). – Mar 03 '22 at 15:57