javalanguagetool

How do I get the Suggested Sentence in a string as output in LanguageTool?


I am using LanguageTool along with Eclipse. The API can be accessed using the link: Click here. I am able to get the text output from it which shows that certain columns have misspelled words but I am not able to get the output which is the corrected string version of the misspelled string given as the input. Here is my code:

JLanguageTool langTool = new JLanguageTool(new BritishEnglish());
List<RuleMatch> matches = langTool.check("A sentence with a error in the Hitchhiker's Guide tot he Galaxy");

for (RuleMatch match : matches) {
  System.out.println("Potential error at line " +
      match.getLine() + ", column " +
      match.getColumn() + ": " + match.getMessage());
  System.out.println("Suggested correction: " +
      match.getSuggestedReplacements());
}

The output obtained is:

Potential error at line 0, column 17: Use <suggestion>an</suggestion> instead of 'a' if the following word starts with a vowel sound, e.g. 'an article', 'an hour'
Suggested correction: [an]
Potential error at line 0, column 32: Possible spelling mistake found
Suggested correction: [Hitch-hiker]
Potential error at line 0, column 51: Did you mean <suggestion>to the</suggestion>?
Suggested correction: [to the]

I would like the output to be the corrected version of the input string as:

A sentence with an error in the Hitchhiker's Guide to the Galaxy

How do I perform this?


Solution

  • Example with using getFromPos(), getToPos() methods:

    private static final String TEST_SENTENCE = "A sentence with a error in the Hitchhiker's Guide tot he Galaxy";
    
    public static void main(String[] args) throws Exception {
    
        StringBuffer correctSentence = new StringBuffer(TEST_SENTENCE);
    
        JLanguageTool langTool = new JLanguageTool(new BritishEnglish());
        List<RuleMatch> matches = langTool.check(TEST_SENTENCE);
    
        int offset = 0;
        for (RuleMatch match : matches) {
    
            correctSentence.replace(match.getFromPos() - offset, match.getToPos() - offset, match.getSuggestedReplacements().get(0));
            offset += (match.getToPos() - match.getFromPos() - match.getSuggestedReplacements().get(0).length());
    
        }
    
        System.out.println(correctSentence.toString());
    }