本文整理汇总了Java中org.languagetool.rules.RuleMatch.getSuggestedReplacements方法的典型用法代码示例。如果您正苦于以下问题:Java RuleMatch.getSuggestedReplacements方法的具体用法?Java RuleMatch.getSuggestedReplacements怎么用?Java RuleMatch.getSuggestedReplacements使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.languagetool.rules.RuleMatch
的用法示例。
在下文中一共展示了RuleMatch.getSuggestedReplacements方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sanitizeText
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
private String sanitizeText(String message) {
String result = message;
try {
List<RuleMatch> matches = helper.getLanguageTool().check(message);
for (RuleMatch match : matches) {
String error = message.substring(match.getFromPos(), match.getToPos());
List<String> replacements = match.getSuggestedReplacements();
if(replacements.size() > 0) {
result = result.replace(error, match.getSuggestedReplacements().get(0));
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return result;
}
示例2: check
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
/**
* Check the text against the compound rule.
* @param expectedErrors the number of expected errors
* @param text the text to check
* @param expSuggestions the expected suggestions
*/
private void check(int expectedErrors, String text, String[] expSuggestions) throws IOException {
assertNotNull("Please initialize langTool!", langTool);
assertNotNull("Please initialize 'rule'!", rule);
RuleMatch[] ruleMatches = rule.match(langTool.getAnalyzedSentence(text));
assertEquals("Expected " + expectedErrors + "errors, but got: " + Arrays.toString(ruleMatches),
expectedErrors, ruleMatches.length);
if (expSuggestions != null && expectedErrors != 1) {
throw new RuntimeException("Sorry, test case can only check suggestion if there's one rule match");
}
if (expSuggestions != null) {
RuleMatch ruleMatch = ruleMatches[0];
String errorMessage =
String.format("Got these suggestions: %s, expected %s ", ruleMatch.getSuggestedReplacements(),
Arrays.toString(expSuggestions));
assertEquals(errorMessage, expSuggestions.length, ruleMatch.getSuggestedReplacements().size());
int i = 0;
for (Object element : ruleMatch.getSuggestedReplacements()) {
String suggestion = (String) element;
assertEquals(expSuggestions[i], suggestion);
i++;
}
}
}
示例3: getRuleMatches
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
@Override
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence);
if (ruleMatches.size() > 0) {
// so 'word' is misspelled:
IrregularForms forms = getIrregularFormsOrNull(word);
if (forms != null) {
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(),
"Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) +
"</suggestion>, the " + forms.formName + " form of the " + forms.posName +
" '" + forms.baseform + "'?");
List<String> allSuggestions = new ArrayList<>();
allSuggestions.addAll(forms.forms);
for (String repl : oldMatch.getSuggestedReplacements()) {
if (!allSuggestions.contains(repl)) {
allSuggestions.add(repl);
}
}
newMatch.setSuggestedReplacements(allSuggestions);
ruleMatches.set(0, newMatch);
}
}
return ruleMatches;
}
示例4: createRuleMatch
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
@Override
protected RuleMatch createRuleMatch(String prevToken, String token, int prevPos, int pos, String msg, AnalyzedSentence sentence) {
boolean doubleI = prevToken.equals("І") && token.equals("і");
if( doubleI ) {
msg += " або, можливо, перша І має бути латинською.";
}
RuleMatch ruleMatch = super.createRuleMatch(prevToken, token, prevPos, pos, msg, sentence);
if( doubleI ) {
List<String> replacements = new ArrayList<>(ruleMatch.getSuggestedReplacements());
replacements.add("I і");
ruleMatch.setSuggestedReplacements(replacements);
}
return ruleMatch;
}
示例5: hasErrorCoveredByMatchAndGoodFirstSuggestion
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
public boolean hasErrorCoveredByMatchAndGoodFirstSuggestion(RuleMatch match) {
if (hasErrorCoveredByMatch(match)) {
List<String> suggestion = match.getSuggestedReplacements();
if (suggestion.size() > 0) {
String firstSuggestion = suggestion.get(0);
for (Error error : errors) {
// The correction from AtD might be "an hour", whereas the error might just span the wrong "a",
// so we just apply the suggestion and see if what we get is the perfect result as specified
// by the corpus:
String correctedByCorpus = error.getAppliedCorrection(markupText);
String correctedByRuleMarkup = markupText.substring(0, match.getFromPos()) +
match.getSuggestedReplacements().get(0) + markupText.substring(match.getToPos());
String correctedByRule = correctedByRuleMarkup.replaceAll("<.*?>", "");
if (correctedByRule.equals(correctedByCorpus)) {
return true;
}
if (error.getCorrection().equalsIgnoreCase(firstSuggestion)) {
return true;
}
}
}
}
return false;
}
示例6: checkFile
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
private void checkFile(File file, JLanguageTool lt) throws IOException {
try (
FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis, "utf-8");
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
List<RuleMatch> matches = lt.check(line);
for (RuleMatch match : matches) {
String covered = line.substring(match.getFromPos(), match.getToPos());
List<String> suggestions = match.getSuggestedReplacements();
List<String> limitedSuggestions = suggestions.subList(0, Math.min(MAX_SUGGESTIONS, suggestions.size()));
System.out.println(covered + ": " + limitedSuggestions);
}
}
}
}
示例7: checkHtmlContent
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
public String checkHtmlContent(String htmlContent) {
AnnotatedText markup = makeAnnotatedText(htmlContent);
StringBuilder bf = new StringBuilder(htmlContent);
langTool.getAllActiveRules().stream().filter(rule -> rule instanceof SpellingCheckRule).forEach(rule -> ((SpellingCheckRule) rule).acceptPhrases(wordsToIgnore));
List<RuleMatch> matches = new ArrayList<>();
try {
matches = langTool.check(markup);
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
int offset = 0;
for (RuleMatch match : matches) {
String desc = match.getMessage();
desc = new HtmlToPlainText().getPlainText(Jsoup.parse(desc));
if (!match.getSuggestedReplacements().isEmpty()) {
desc += Configuration.getBundle().getString("ui.alert.correction.tooltip.suggestion")
+ match.getSuggestedReplacements();
}
String before = "<span class=\"error-french\" title=\"" + desc + "\">";
bf.insert(match.getFromPos() + offset, before);
offset += before.length();
String after = "</span> ";
bf.insert(match.getToPos() + offset, after);
offset += after.length();
}
return bf.toString();
}
示例8: checkHtmlContentToText
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
public String checkHtmlContentToText(String htmlContent, String source) {
AnnotatedText markup = makeAnnotatedText(htmlContent);
StringBuilder bf = new StringBuilder();
langTool.getAllActiveRules().stream().filter(rule -> rule instanceof SpellingCheckRule).forEach(rule -> ((SpellingCheckRule) rule).addIgnoreTokens(wordsToIgnore));
List<RuleMatch> matches = new ArrayList<>();
try {
matches = langTool.check(markup);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
for (RuleMatch match : matches) {
String txt = htmlContent.substring(match.getFromPos(), match.getToPos());
bf.append("\n\n");
bf.append("> ");
bf.append(markup.getPlainText().split("[\n|\r]")[match.getLine()].replace(txt, "**" + txt + "**"));
bf.append("\n");
bf.append(Configuration.getBundle().getString("ui.alert.correction.source")).append(source);
bf.append("\n\n");
bf.append(match.getRule().getDescription());
bf.append("\n\n");
for (String s : match.getSuggestedReplacements()) {
bf.append("- ").append(s).append("\n");
}
}
return bf.toString();
}
示例9: TextMatch
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
public TextMatch(RuleMatch match) {
this.line = match.getLine();
this.column = match.getColumn();
this.endColumn = match.getEndColumn();
this.endLine = match.getEndLine();
this.fromPos = match.getFromPos();
this.toPos = match.getToPos();
this.message = match.getMessage();
this.ruleId = match.getRule().getId();
this.replacements = match.getSuggestedReplacements();
}
示例10: getBestHashtagReplacement
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
private String getBestHashtagReplacement(String hashtag){
try {
if(hashtag.startsWith("#"))
hashtag=hashtag.substring(1);
Matcher mtchrPunc = ptrnPunc.matcher(hashtag);
String punct="";
if(mtchrPunc.find()){
int pos_punct=mtchrPunc.start();
if(pos_punct>-1)
punct=hashtag.substring(pos_punct);
}
hashtag=hashtag.replaceAll("\\p{Punct}","");
List<RuleMatch> matches = langTool.check(hashtag);
String bestMatch=hashtag;
int largestBit=1;
for (RuleMatch match : matches) {
List<String> replacements=match.getSuggestedReplacements();
for(String str:replacements){
String[] parts=str.split(" ");
String new_str=str.replaceAll(" ","");
if((new_str.equals(hashtag))&&(parts.length>largestBit)){
largestBit=parts.length;
bestMatch=str;
}
}
}
return bestMatch+punct;
} catch (IOException ex) {
Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex);
return hashtag;
}
}
示例11: writeReplacements
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
private void writeReplacements(JsonGenerator g, RuleMatch match) throws IOException {
g.writeArrayFieldStart("replacements");
for (String replacement : match.getSuggestedReplacements()) {
g.writeStartObject();
g.writeStringField("value", replacement);
g.writeEndObject();
}
g.writeEndArray();
}
示例12: printMatches
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
/**
* Displays matches in a simple text format.
* @param ruleMatches Matches from rules.
* @param prevMatches Number of previously found matches.
* @param contents The text that was checked.
* @param contextSize The size of contents displayed.
* @since 1.0.1
*/
private static void printMatches(List<RuleMatch> ruleMatches,
int prevMatches, String contents, int contextSize) {
int i = 1;
ContextTools contextTools = new ContextTools();
contextTools.setContextSize(contextSize);
for (RuleMatch match : ruleMatches) {
Rule rule = match.getRule();
String output = i + prevMatches + ".) Line " + (match.getLine() + 1) + ", column "
+ match.getColumn() + ", Rule ID: " + rule.getId();
if (rule instanceof AbstractPatternRule) {
AbstractPatternRule pRule = (AbstractPatternRule) rule;
if (pRule.getSubId() != null) {
output += "[" + pRule.getSubId() + "]";
}
}
System.out.println(output);
String msg = match.getMessage();
msg = msg.replaceAll("</?suggestion>", "'");
System.out.println("Message: " + msg);
List<String> replacements = match.getSuggestedReplacements();
if (!replacements.isEmpty()) {
System.out.println("Suggestion: " + String.join("; ", replacements));
}
System.out.println(contextTools.getPlainTextContext(match.getFromPos(), match.getToPos(), contents));
if (rule.getUrl() != null) {
System.out.println("More info: " + rule.getUrl());
}
if (i < ruleMatches.size()) {
System.out.println();
}
i++;
}
}
示例13: handleResult
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
@Override
protected void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language) {
if (ruleMatches.size() > 0) {
int i = 1;
System.out.println("\nTitle: " + sentence.getTitle());
for (RuleMatch match : ruleMatches) {
String output = i + ".) Line " + (match.getLine() + 1) + ", column "
+ match.getColumn() + ", Rule ID: " + match.getRule().getId();
if (match.getRule() instanceof AbstractPatternRule) {
AbstractPatternRule pRule = (AbstractPatternRule) match.getRule();
output += "[" + pRule.getSubId() + "]";
}
System.out.println(output);
String msg = match.getMessage();
msg = msg.replaceAll("<suggestion>", "'");
msg = msg.replaceAll("</suggestion>", "'");
System.out.println("Message: " + msg);
List<String> replacements = match.getSuggestedReplacements();
if (!replacements.isEmpty()) {
System.out.println("Suggestion: " + String.join("; ", replacements));
}
System.out.println(contextTools.getPlainTextContext(match.getFromPos(), match.getToPos(), sentence.getText()));
i++;
checkMaxErrors(++errorCount);
}
}
checkMaxSentences(++sentenceCount);
}
示例14: createSpellCheckIssueObject
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
private void createSpellCheckIssueObject(SensorContext sensorContext,
InputFile inputFile,
Node node,
RuleMatch match) {
// TODO: Don't hardcode the ruleKey
RuleKey ruleKey = RuleKey.of(GherkinRulesDefinition.REPOSITORY_NAME, "SpellCheck");
try {
TextRange textRange = inputFile.newRange(
node.getLocation().getLine(),
match.getColumn(),
node.getLocation().getLine(),
match.getEndColumn()
);
NewIssue newIssue = sensorContext.newIssue();
String suggestedReplace = "";
if (!match.getSuggestedReplacements().isEmpty()) {
suggestedReplace = " - replace it with:";
for (String suggest: match.getSuggestedReplacements()
) {
suggestedReplace = suggestedReplace + " " + suggest + ";";
}
}
NewIssueLocation primaryLocation = newIssue.newLocation()
.message(match.getMessage() + suggestedReplace)
.on(inputFile)
.at(textRange);
newIssue.forRule(ruleKey).at(primaryLocation);
newIssue.save();
} catch (IllegalArgumentException iarg) {
LOG.error("SpellCheck rule is an error when create issue: \n" +
"file is: " + inputFile.relativePath() + "\n" +
"match is:" + match.getMessage() + "\n" +
"line is:" + node.getLocation().getLine() + "\n" +
"offsets is: start - " + match.getColumn() + " to " + match.getEndColumn(),
iarg);
}
}
示例15: applySuggestionsToOriginalText
import org.languagetool.rules.RuleMatch; //导入方法依赖的package包/类
/**
* Applies the suggestions from the rule to the original text. For rules that
* have no suggestion, a pseudo-correction is generated that contains the same
* text as before.
*/
public List<RuleMatchApplication> applySuggestionsToOriginalText(RuleMatch match) {
List<String> replacements = new ArrayList<>(match.getSuggestedReplacements());
boolean hasRealReplacements = replacements.size() > 0;
if (!hasRealReplacements) {
// create a pseudo replacement with the error text itself
String plainText = textMapping.getPlainText();
replacements.add(plainText.substring(match.getFromPos(), match.getToPos()));
}
List<RuleMatchApplication> ruleMatchApplications = new ArrayList<>();
Location fromPosLocation = textMapping.getOriginalTextPositionFor(match.getFromPos() + 1); // not zero-based!
Location toPosLocation = textMapping.getOriginalTextPositionFor(match.getToPos() + 1);
/*System.out.println("=========");
System.out.println(textMapping.getMapping());
System.out.println("=========");
System.out.println(textMapping.getPlainText());
System.out.println("=========");
System.out.println(originalText);
System.out.println("=========");*/
int fromPos = LocationHelper.absolutePositionFor(fromPosLocation, originalText);
int toPos = LocationHelper.absolutePositionFor(toPosLocation, originalText);
for (String replacement : replacements) {
String errorText = textMapping.getPlainText().substring(match.getFromPos(), match.getToPos());
// the algorithm is off a bit sometimes due to the complex syntax, so consider the next whitespace:
int contextFrom = findNextWhitespaceToTheLeft(originalText, fromPos);
int contextTo = findNextWhitespaceToTheRight(originalText, toPos);
/*System.out.println(match + ":");
System.out.println("match.getFrom/ToPos(): " + match.getFromPos() + "/" + match.getToPos());
System.out.println("from/toPosLocation: " + fromPosLocation + "/" + toPosLocation);
System.out.println("from/toPos: " + fromPos + "/" + toPos);
System.out.println("contextFrom/To: " + contextFrom + "/" + contextTo);*/
String context = originalText.substring(contextFrom, contextTo);
String text = originalText.substring(0, contextFrom)
+ errorMarker.getStartMarker()
+ context
+ errorMarker.getEndMarker()
+ originalText.substring(contextTo);
String newContext;
if (StringUtils.countMatches(context, errorText) == 1) {
newContext = context.replace(errorText, replacement);
} else {
// This may happen especially for very short strings. As this is an
// error, we don't claim to have real replacements:
newContext = context;
hasRealReplacements = false;
}
String newText = originalText.substring(0, contextFrom)
// we do a simple string replacement as that works even if our mapping is off a bit:
+ errorMarker.getStartMarker()
+ newContext
+ errorMarker.getEndMarker()
+ originalText.substring(contextTo);
RuleMatchApplication application;
if (hasRealReplacements) {
application = RuleMatchApplication.forMatchWithReplacement(match, text, newText, errorMarker);
} else {
application = RuleMatchApplication.forMatchWithoutReplacement(match, text, newText, errorMarker);
}
ruleMatchApplications.add(application);
}
return ruleMatchApplications;
}