当前位置: 首页>>代码示例>>Java>>正文


Java RuleMatch类代码示例

本文整理汇总了Java中org.languagetool.rules.RuleMatch的典型用法代码示例。如果您正苦于以下问题:Java RuleMatch类的具体用法?Java RuleMatch怎么用?Java RuleMatch使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RuleMatch类属于org.languagetool.rules包,在下文中一共展示了RuleMatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public static void main(String[] args) {
	System.out.println("start...");
	try {
		JLanguageTool langTool = new JLanguageTool(Language.ENGLISH);
		langTool.activateDefaultPatternRules();
		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.getEndLine() + ", column " + match.getColumn()
					+ ": " + match.getMessage());
			System.out.println("Suggested correction: "
					+ match.getSuggestedReplacements());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	System.out.println("finished.");
}
 
开发者ID:kennanmeyer,项目名称:SE-410-Project,代码行数:20,代码来源:TestLangTool.java

示例2: spellcheckDocument

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public boolean spellcheckDocument() {
    editorToolBar.setActionText("Spell checking document \'" + file.getName() + "\'");
    Platform.runLater(() -> {
        try {
            timer.start();
            List<RuleMatch> matches = spellcheck.check(getContent());
            MarkdownHighligher.computeSpellcheckHighlighting(matches, this);
            editorToolBar.setActionText("Found " + matches.size() + " misspellings in the document \'" + file.getName() + "\' (" + timer.end() + "ms)");
        } catch (IOException e) {
            dialogFactory.buildExceptionDialogBox(
                    dict.DIALOG_EXCEPTION_TITLE,
                    dict.DIALOG_EXCEPTION_SPELLCHECK_CONTENT,
                    e.getMessage(),
                    e
            );
        }
    });

    return true;
}
 
开发者ID:jdesive,项目名称:textmd,代码行数:21,代码来源:EditorPane.java

示例3: check

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public List<RuleMatch> check(String text) throws IOException {
    List<RuleMatch> matches = languageTool.check(text);
    matches = matches.stream().filter(match -> {
        String str = text.substring(match.getFromPos(), match.getToPos());
        if(Lists.newArrayList(spellcheckExcluded).contains(str)){
            return false;
        }
        for(String ex : spellcheckExcludedTags){
            if(str.startsWith(ex) || str.endsWith(ex)){
                return false;
            }
        }
        logger.debug("Found misspelling \'{}\' at {} to {}", str, match.getFromPos(), match.getToPos());
        return true;
    }).collect(Collectors.toList());
    logger.debug("Found " + matches.size() + " misspellings in current document");
    return matches;
}
 
开发者ID:jdesive,项目名称:textmd,代码行数:19,代码来源:Spellcheck.java

示例4: 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;
}
 
开发者ID:dbpedia,项目名称:chatbot,代码行数:18,代码来源:TextHandler.java

示例5: processMatches

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
/**
 * Tdestings
 * 
 * @param collector
 * @param matches
 */

private void processMatches(ISpellingProblemCollector collector, List<RuleMatch> matches) {
	WorkspaceModifyOperation workspaceRunnable = new WorkspaceModifyOperation() {
		@Override
		protected void execute(IProgressMonitor monitor)
				throws CoreException, InvocationTargetException, InterruptedException {
			// TODO
			deleteMarkers();
			matches.forEach(match -> {
				collector.accept(new LTSpellingProblem(match));
				addMarker(match);
			});
		}

	};

	try {
		workspaceRunnable.run(null);
	} catch (InvocationTargetException | InterruptedException e) {
		e.printStackTrace();
	}
}
 
开发者ID:vogellacompany,项目名称:languagetool-eclipse-plugin,代码行数:29,代码来源:Engine.java

示例6: onViewPortChanged

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public void onViewPortChanged(Object editor, int from, int to)
{
    logger.debug("viewport changed");
    Platform.runLater(() -> {
        int fromIndex = (int) webview.getEngine().executeScript("editor.indexFromPos({line:" + from + ",ch: 0});");
        int toIndex = (int) webview.getEngine().executeScript("editor.indexFromPos({line:" + (to + 1) +",ch: 0});");

        String text = getCode();
        text = text.substring(fromIndex, toIndex);
        List<RuleMatch> results = checkText(text);
        for (RuleMatch result : results)
        {
            int resultFromIndex = result.getFromPos();
            int resultToIndex = result.getToPos();
            webview.getEngine().executeScript("editor.markText(editor.posFromIndex(" + (fromIndex + resultFromIndex) + "), editor.posFromIndex(" + (fromIndex + resultToIndex) + ")," +
                    "{\"className\": \"cm-spell-error\"})");
        }
    });
}
 
开发者ID:finanzer,项目名称:epubfx,代码行数:20,代码来源:AbstractCodeEditor.java

示例7: spellCheckAllText

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public void spellCheckAllText() throws BadLocationException {   
    Document doc = etc.getrSyntaxTextArea().getDocument();   
    if (doc != null) {                                                
        String editorText = etc.getrSyntaxTextArea().getText(0, doc.getLength());            
        if (editorText != null) {  
            Highlighter highlighter = etc.getrSyntaxTextArea().getHighlighter();                                      
            if(etc.getEditorState().isHighlighted()) {  
                List<RuleMatch> matches = null;  
                try {
                    matches = etc.getLangTool().check(editorText);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }

                //Highlight the spelling check results
                for (RuleMatch match : matches) {
                    highlighter.addHighlight(match.getFromPos(), match.getToPos(), etc.getPainter());   
                }                        
            } else {  
                highlighter.removeAllHighlights();
            }
        }
    }        
}
 
开发者ID:sebbrudzinski,项目名称:Open-LaTeX-Studio,代码行数:25,代码来源:SpellCheckService.java

示例8: testIgnoreSuggestionsWithMorfologik

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
@Test
public void testIgnoreSuggestionsWithMorfologik() throws IOException {
  JLanguageTool lt = new JLanguageTool(new AmericanEnglish());

  assertThat(lt.check("This is anArtificialTestWordForLanguageTool.").size(), is(0));   // no error, as this word is in ignore.txt
  assertThat(lt.check("How an ab initio calculation works.").size(), is(0));   // As a multi-word entry in spelling.txt "ab initio" must be accepted
  assertThat(lt.check("Test adjoint").size(), is(0));   // in spelling.txt
  assertThat(lt.check("Test Adjoint").size(), is(0));   // in spelling.txt (lowercase)

  List<RuleMatch> matches2 = lt.check("This is a real typoh.");
  assertThat(matches2.size(), is(1));
  assertThat(matches2.get(0).getRule().getId(), is("MORFOLOGIK_RULE_EN_US"));

  List<RuleMatch> matches3 = lt.check("This is anotherArtificialTestWordForLanguageTol.");  // note the typo
  assertThat(matches3.size(), is(1));
  assertThat(matches3.get(0).getSuggestedReplacements().toString(), is("[anotherArtificialTestWordForLanguageTool]"));
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:18,代码来源:SpellingCheckRuleTest.java

示例9: match

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
  List<RuleMatch> ruleMatches = new ArrayList<>();
  AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace();
  for (int i = 1; i < tokens.length; i++) {
    String token = tokens[i].getToken();
    if (getSubjects().contains(token)) {
      String[] context = getContext(tokens, i);
      float[] y = classifier.getScores(context);
      Suggestion suggestion = getSuggestion(y);
      if (!suggestion.matches(token)) {
        if (!suggestion.isUnsure()) {
          ruleMatches.add(createRuleMatch(tokens[i], suggestion, y));
        } else {
          if (DEBUG) {
            System.out.println("unsure: " + getMessage(suggestion, y) + Arrays.toString(context));
          }
        }
      }
    }
  }
  return toRuleMatchArray(ruleMatches);
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:24,代码来源:NeuralNetworkRule.java

示例10: testRule

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
@Test
public void testRule() throws IOException {

  // correct sentences:
  assertEquals(0, rule.match(langTool.getAnalyzedSentence("It wasn't me.")).length);
  assertEquals(0, rule.match(langTool.getAnalyzedSentence("I'm ill.")).length);
  assertEquals(0, rule.match(langTool.getAnalyzedSentence("Staatszerfall im südlichen Afrika.")).length);

  // incorrect sentences:

  // at the beginning of a sentence
  checkSimpleReplaceRule("Wasnt this great", "Wasn't");
  checkSimpleReplaceRule("YOURE WRONG", "YOU'RE");
  checkSimpleReplaceRule("Dont do this", "Don't");
  // inside sentence
  checkSimpleReplaceRule("It wasnt me", "wasn't");
  checkSimpleReplaceRule("You neednt do this", "needn't");
  checkSimpleReplaceRule("I know Im wrong", "I'm");

  //two suggestions
  final RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence("Whereve you are"));
  assertEquals(2, matches[0].getSuggestedReplacements().size());
  assertEquals("Where've", matches[0].getSuggestedReplacements().get(0));
  assertEquals("Wherever", matches[0].getSuggestedReplacements().get(1));

}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:27,代码来源:ContractionSpellingRuleTest.java

示例11: checkCorrections

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
private void checkCorrections(Rule rule, IncorrectExample incorrectExample, List<String> xmlLines, JLanguageTool tool) throws IOException {
  List<String> corrections = incorrectExample.getCorrections();
  if (corrections.isEmpty()) {
    for (Rule r : tool.getAllActiveRules()) {
      tool.disableRule(r.getId());
    }
    tool.enableRule(rule.getId());
    String incorrectSentence = incorrectExample.getExample().replaceAll("</?marker>", "");
    List<RuleMatch> matches = tool.check(incorrectSentence);
    System.err.println("no corrections: " + rule.getId() + ", " + matches.size() + " matches");
    if (matches.size() == 0) {
      throw new RuntimeException("Got no rule match: " + incorrectSentence);
    }
    List<String> suggestedReplacements = matches.get(0).getSuggestedReplacements();
    String newAttribute = "correction=\"" + String.join("|", suggestedReplacements) + "\"";
    addAttribute(rule, newAttribute, xmlLines);
  }
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:19,代码来源:ExampleSentenceCorrectionCreator.java

示例12: getRuleMatches

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence) throws IOException {
  List<RuleMatch> ruleMatches = new ArrayList<>();
  if (isMisspelled(speller1, word) || isProhibited(word)) {
    RuleMatch ruleMatch = new RuleMatch(this, sentence, startPos, startPos
        + word.length(), messages.getString("spelling"),
        messages.getString("desc_spelling_short"));
    List<String> suggestions = speller1.getSuggestions(word);
    if (suggestions.isEmpty() && word.length() >= 5) {
      // speller1 uses a maximum edit distance of 1, it won't find suggestion for "garentee", "greatful" etc.
      suggestions.addAll(speller2.getSuggestions(word));
      if (suggestions.isEmpty()) {
        suggestions.addAll(speller3.getSuggestions(word));
      }
    }
    suggestions.addAll(0, getAdditionalTopSuggestions(suggestions, word));
    suggestions.addAll(getAdditionalSuggestions(suggestions, word));
    if (!suggestions.isEmpty()) {
      filterSuggestions(suggestions);
      ruleMatch.setSuggestedReplacements(orderSuggestions(suggestions, word));
    }
    ruleMatches.add(ruleMatch);
  }
  return ruleMatches;
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:25,代码来源:MorfologikSpellerRule.java

示例13: testWithException

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
public void testWithException() throws Exception {
  createIndex("How to move back and fourth from linux to xmb?");
  PatternToken exceptionElem = new PatternToken("forth|back", false, true, false);
  exceptionElem.setStringPosException("exception", false, false, false, false, false, "POS", false, false, null);
  List<PatternToken> patternTokens = Arrays.asList(
      new PatternToken("move", false, false, false),
      exceptionElem
      );
  PatternRule rule1 = new PatternRule("RULE1", new English(), patternTokens, "desc", "msg", "shortMsg");
  Searcher errorSearcher = new Searcher(directory);
  SearcherResult searcherResult = errorSearcher.findRuleMatchesOnIndex(rule1, new English());
  assertEquals(1, searcherResult.getCheckedSentences());
  assertEquals(1, searcherResult.getMatchingSentences().size());
  List<RuleMatch> ruleMatches = searcherResult.getMatchingSentences().get(0).getRuleMatches();
  assertEquals(1, ruleMatches.size());
  Rule rule = ruleMatches.get(0).getRule();
  assertEquals("RULE1", rule.getId());
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:19,代码来源:IndexerSearcherTest.java

示例14: performCheck

import org.languagetool.rules.RuleMatch; //导入依赖的package包/类
@Override
protected List<RuleMatch> performCheck(List<AnalyzedSentence> analyzedSentences, List<String> sentences,
     List<Rule> allRules, ParagraphHandling paraMode, 
     AnnotatedText annotatedText, RuleMatchListener listener) throws IOException {
  int charCount = 0;
  int lineCount = 0;
  int columnCount = 1;

  List<RuleMatch> ruleMatches = new ArrayList<>();
  
  ExecutorService executorService = getExecutorService();
  try {
    List<Callable<List<RuleMatch>>> callables =
            createTextCheckCallables(paraMode, annotatedText, analyzedSentences, sentences, allRules, charCount, lineCount, columnCount, listener);
    List<Future<List<RuleMatch>>> futures = executorService.invokeAll(callables);
    for (Future<List<RuleMatch>> future : futures) {
      ruleMatches.addAll(future.get());
    }
  } catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }
  
  return ruleMatches;
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:25,代码来源:MultiThreadedJLanguageTool.java

示例15: 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++;
    }
  }
}
 
开发者ID:languagetool-org,项目名称:languagetool,代码行数:30,代码来源:EnglishDashRuleTest.java


注:本文中的org.languagetool.rules.RuleMatch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。