HMdeveloper
HMdeveloper

Reputation: 2884

number possible part of speech of the word

I know how to get pos of a word in the text but I need to know what would be the possible pos of a word in a sentence for example "like" can have 4 part of speechs: verb noun preposition .... Is it possible to get that from Stanford library?

Upvotes: 2

Views: 414

Answers (1)

John Wiseman
John Wiseman

Reputation: 3137

Stanford CoreNLP doesn't seem to have an interface to WordNet, but it's pretty easy to do this with one of the other small Java WordNet libraries. For this example, I used JWI 2.3.3.

Besides JWI, you'll need to download a copy of the WordNet database. For example, you can download WordNet-3.0.tar.gz from Princeton. Untar the dictionary.

The following code includes a function that returns a list of the possible parts of speech for a word:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import edu.mit.jwi.Dictionary;
import edu.mit.jwi.item.POS;
import edu.mit.jwi.item.IIndexWord;
import edu.mit.jwi.morph.WordnetStemmer;

public class WNDemo {

  /**
   * Given a dictionary and a word, find all the parts of speech the
   * word can be.
   */
  public static Collection getPartsOfSpeech(Dictionary dict, String word) {
    ArrayList<POS> parts = new ArrayList<POS>();
    WordnetStemmer stemmer = new WordnetStemmer(dict);
    // Check every part of speech.
    for (POS pos : POS.values()) {
      // Check every stem, because WordNet doesn't have every surface
      // form in its database.
      for (String stem : stemmer.findStems(word, pos)) {
        IIndexWord iw = dict.getIndexWord(stem, pos);
        if (iw != null) {
          parts.add(pos);
        }
      }
    }
    return parts;
  }

  public static void main(String[] args) {
    try {
      Dictionary dict = new Dictionary(new File("WordNet-3.0/dict"));
      dict.open();
      System.out.println("'like' is a " + getPartsOfSpeech(dict, "like"));
    } catch (IOException e) {
      System.err.println("Error: " + e);
    }
  }
}

And the output:

'like' is a [noun, verb, adjective]

Upvotes: 3

Related Questions