I am trying tokenize strings into ngrams. Strangely in the documentation for the NGramTokenizer I do not see a method that will return the individual ngrams that were tokenized. In fact I only see two methods in the NGramTokenizer class that return String Objects.
Here is the code that I have:
Reader reader = new StringReader("This is a test string");
NGramTokenizer gramTokenizer = new NGramTokenizer(reader, 1, 3);
- Where are the ngrams that were tokenized?
- How can I get the output in Strings/Words?
I want my output to be like: This, is, a, test, string, This is, is a, a test, test string, This is a, is a test, a test string.
Without creating a test program, I would guess that incrementToken() returns the next token which will be one of the ngrams.
For example, using ngram lengths of 1-3 with the string 'a b c d', NGramTokenizer could return:
where 'a', 'a b', etc. are the resulting ngrams.
[Edit]
You might also want to look at Querying lucene tokens without indexing, as it talks about peeking into the token stream.
package ngramalgoimpl; import java.util.*;
public class ngr {
}
For recent version of Lucene (4.2.1), this is a clean code which works. Before executing this code, you have to import 2 jar files:
Find these files at http://www.apache.org/dyn/closer.cgi/lucene/java/4.2.1
I don't think you'll find what you're looking for trying to find methods returning String. You'll need to deal with Attributes.
Should work something like:
Be sure to reset() the Tokenizer it if it needs to be reused after that, though.
Tokenizing grouping of words, rather than chars, per comments: