The necessary steps include the following:
- Add the following imports to the project:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import com.aliasi.hmm.HiddenMarkovModel;
import com.aliasi.hmm.HmmDecoder;
import com.aliasi.tag.ScoredTagging;
import com.aliasi.tag.Tagging;
- In the main method, add the following statements to define a sample text and a try-with-resources block to create input streams to load a model:
String sampleSentence = "When the mouse saw the cat it ran away.";
try (FileInputStream fileInputStream =
new FileInputStream("pos-en-general-brown.HiddenMarkovModel");
ObjectInputStream objectInputStream =
new ObjectInputStream(fileInputStream);) {
…
} catch (IOException ex) {
// Handle exceptions
} catch (ClassNotFoundException ex) {
// Handle exceptions
}
- Create the model and a POS tagger with the following declarations:
HiddenMarkovModel hiddenMarkovModel =
(HiddenMarkovModel) objectInputStream.readObject();
HmmDecoder hmmDecoder = new HmmDecoder(hiddenMarkovModel);
- Add the following statements to find the POS elements and display them:
List<String> tokenList = Arrays.asList(sampleSentence.split(" "));
Tagging<String> taggingString = hmmDecoder.tag(tokenList);
for (int i = 0; i < taggingString.size(); ++i) {
System.out.print(taggingString.token(i) + "/" +
taggingString.tag(i) + " ");
}
System.out.println();
- Execute the program. You will get the following output:
When/wrb the/at mouse/nn saw/vbd the/at cat/nn it/pps ran/vbd away./nn