2011-01-10 3 views
1

두 개 이상의 단어를 검사 할 수 있고 Java 지식이 너무 제한되어 직접 변경하기 위해이 스크립트를 수정해야합니다. 이 스크립트는 OpenOffice (LanguageTool)의 opensource 문법 검사기의 일부이며 스크립트 목적은 특정 단어를 다른 단어로 바꾸는 것입니다.이 자바 코드에서 두 개 이상의 단어를 검사하는 방법

확인하는 단어의 파일은 "coherency.txt"라고하고 형식의되고이 같다 : WrongWord1 = CorrectWord1 WrongWord2 = CorrectWord2

을 내가 입력 할 때 : WrongWord1이 스크립트에 의해 플래그되고 대신 CorrectWord1을 사용해야한다고 알려줍니다. 내가 WrongWord3를 입력 ​​할 때 은 그게

입니다 WrongWord1 = WrongWord2 = CorrectWord1 WrongWord3 = WrongWord4 = WrongWord5 = CorrectWord2 WrongWord6 = CorrectWord3 그래서 :

는하지만 다음과 같이 세 단어 이상을 할 수 있어야합니다 플래그 및 스크립트 내가 그것을 또한 플래그가 WrongWord2를 입력하고 스크립트는 내가 http://www.sbbic.org/lang/en-us/volunteer/

0123에서 웹 페이지로 연결되는 링크를 넣을 수 있습니다 도움이 될 수 있다면 나는 CorrectWord1

를 사용해야 저를 말할 때 내가 CorrectWord2 또는 를 사용해야 하더군요

이 코드를 수정하여 둘 이상의 단어를 비교 한 결과 대체 할 수있는 방법에 대해 도움을 주시면 대단히 감사하겠습니다! 감사 네이 작은 적응 용

/* LanguageTool, a natural language style checker 
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) 
* 
* This library is free software; you can redistribute it and/or 
* modify it under the terms of the GNU Lesser General Public 
* License as published by the Free Software Foundation; either 
* version 2.1 of the License, or (at your option) any later version. 
* 
* This library is distributed in the hope that it will be useful, 
* but WITHOUT ANY WARRANTY; without even the implied warranty of 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* Lesser General Public License for more details. 
* 
* You should have received a copy of the GNU Lesser General Public 
* License along with this library; if not, write to the Free Software 
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 
* USA 
*/ 
package de.danielnaber.languagetool.rules; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Locale; 
import java.util.Map; 
import java.util.ResourceBundle; 

import de.danielnaber.languagetool.AnalyzedSentence; 
import de.danielnaber.languagetool.AnalyzedTokenReadings; 
import de.danielnaber.languagetool.JLanguageTool; 
import de.danielnaber.languagetool.tools.StringTools; 

/** 
* A Khmer rule that matches words or phrases which should not be used and suggests 
* correct ones instead. Loads the relevant words from 
* <code>rules/km/coherency.txt</code>, where km is a code of the language. 
* 
* @author Andriy Rysin 
*/ 
public abstract class KhmerWordCoherencyRule extends KhmerRule { 

    private Map<String, String> wrongWords; // e.g. "вреѿті реѿт" -> "зреѿтою" 

    private static final String FILE_NAME = "/km/coherency.txt"; 

    public abstract String getFileName(); 

    private static final String FILE_ENCODING = "utf-8"; 

    public String getEncoding() { 
    return FILE_ENCODING; 
    } 

    /** 
    * Indicates if the rule is case-sensitive. Default value is <code>true</code>. 
    * @return true if the rule is case-sensitive, false otherwise. 
    */ 
    public boolean isCaseSensitive() { 
    return false; 
    } 

    /** 
    * @return the locale used for case conversion when {@link #isCaseSensitive()} is set to <code>false</code>. 
    */ 
    public Locale getLocale() { 
    return Locale.getDefault(); 
    } 

    public KhmerWordCoherencyRule(final ResourceBundle messages) throws IOException { 
    if (messages != null) { 
     super.setCategory(new Category(messages.getString("category_misc"))); 
    } 
    wrongWords = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream(getFileName())); 
    } 

    public String getId() { 
    return "KM_WORD_COHERENCY"; 
    } 

    public String getDescription() { 
    return "Checks for wrong words/phrases"; 
    } 

    public String getSuggestion() { 
    return " is not valid, use "; 
    } 

    public String getShort() { 
    return "Wrong word"; 
    } 

    public final RuleMatch[] match(final AnalyzedSentence text) { 
    final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>(); 
    final AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace(); 

    for (int i = 1; i < tokens.length; i++) { 
     final String token = tokens[i].getToken(); 

     final String origToken = token; 
     final String replacement = isCaseSensitive()?wrongWords.get(token):wrongWords.get(token.toLowerCase(getLocale())); 
     if (replacement != null) { 
     final String msg = token + getSuggestion() + replacement; 
     final int pos = tokens[i].getStartPos(); 
     final RuleMatch potentialRuleMatch = new RuleMatch(this, pos, pos 
      + origToken.length(), msg, getShort()); 
     if (!isCaseSensitive() && StringTools.startsWithUppercase(token)) { 
      potentialRuleMatch.setSuggestedReplacement(StringTools.uppercaseFirstChar(replacement)); 
     } else { 
      potentialRuleMatch.setSuggestedReplacement(replacement); 
     } 
     ruleMatches.add(potentialRuleMatch); 
     } 
    } 
    return toRuleMatchArray(ruleMatches); 
    } 


    private Map<String, String> loadWords(final InputStream file) throws IOException { 
    final Map<String, String> map = new HashMap<String, String>(); 
    InputStreamReader isr = null; 
    BufferedReader br = null; 
    try { 
     isr = new InputStreamReader(file, getEncoding()); 
     br = new BufferedReader(isr); 
     String line; 

     while ((line = br.readLine()) != null) { 
     line = line.trim(); 
     if (line.length() < 1) { 
      continue; 
     } 
     if (line.charAt(0) == '#') { // ignore comments 
      continue; 
     } 
     final String[] parts = line.split("="); 
     if (parts.length != 2) { 
      throw new IOException("Format error in file " 
       + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(getFileName()) + ", line: " + line); 
     } 
     map.put(parts[0], parts[1]); 
     } 

    } finally { 
     if (br != null) { 
     br.close(); 
     } 
     if (isr != null) { 
     isr.close(); 
     } 
    } 
    return map; 
    } 

    public void reset() { 
    } 

} 
+0

당신은 너무 많은 코드를 기록했다. 문제를 나타내는 코드를 게시하십시오. 네 문제가 뭔지도 모르겠다. – Falmarri

+0

누군가가 묻는 것을하면, 조정 된 소스 코드를 컴파일 할 수있는 전문 지식을 갖추고 있으며, 필요한 경우 컴파일 된 모든 소스를 JAR 파일에 다시 패키징합니까? 조정 된 소스를 대체하여 간단하게 "작동"하지 않기 때문입니다. –

+1

당신은 * word1 = wrongword2 *와 같고 * wrongword2 = word1 *이 아닌 것이 확실합니까? – Hons

답변

1

: 올바른의

키가 잘못된 단어 것이다

WrongWord = CorrectWord[, CorrectWord]* 

에 원하는 입력 형식을 변경 고려 값은 쉼표로 구분 대안. 따라서 파일을 그대로 파싱 할 수 있습니다.

맵의 유형은 Map<String, Set<String>>이어야하며 각 토큰은 대체 세트로 매핑됩니다.

이제 각 줄을 =으로 분할하여 키/값 쌍을 얻고 , 주위의 각 값을 입력하여 제안 된 토큰의 배열을 가져 와서 입력을 대체 할 수 있습니다. 이제 두 개 이상의 제안을 기대하기 때문에


는 그런 다음, 새 메시지를 조립하는 일 match에 약간 수정을해야합니다.

변경

final String[] replacements = wrongWords.get(token); 
    if (replacements != null) { 
    final String msg = createMessage(token, replacements); 
    final int pos = tokens[i].getStartPos(); 

-final String origToken = token; 후 라인은 사용자에게 토큰에 대한 많은 대안의 하나를 알려주는 사람이 읽을 수있는 메시지를 반환하는 createMessage 방법을 구현한다.

final String[] parts = line.split("="); 
if (parts.length != 2) { 
    throw new IOException("Format error in file " + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(getFileName()) + ", line: " + line); 
} 
map.put(parts[0], parts[1]); 

이 하나의 키와 맵에 값으로 오른쪽으로 등호의 왼쪽을두고 :

+0

당신은 맞습니다. 안드레아스 - 저는 현실과 일치시키기 위해 질문을 바꾸 었습니다. 감사! – Nathan

+0

나는 coherency.txt 파일에서 Word = WrongWord [, WrongWord] *를 넣어야한다는 것을 이해하고 있습니까? 내가 이해할 수 있도록 실제 단어 예를 들어 보겠습니다. Hello = 안녕 [Hullo, Hiya] * 아니면 Hello 여야 하는가 [Hullo, Hi] * ("안녕하십니까? – Nathan

+1

@Nathan - 매우 일반적인 구문을 선택했습니다.이 패턴과 일치하는 실제 줄은 'Wrong1 = Correct1'과 'Wrong2 = Correct2a, Correct2b'가 될 수 있습니다. –

1

변경해야하는 것은 loadWords에서이 부분입니다.그러므로 나는 왼편이 틀린 말이어야한다고 생각한다. 그러므로 입력 내용은 wrong1 = wrong2 = ... = correct이되어야합니다. 아마 그것이 가장 효율적인 해결책이 아니다

wrong1 = correct 
wrong2 = correct 
wrong3 = correct 
... 

을하지만 :이 설정

당신은 단순히지도에 folowing 항목을 생성 할 것이다 다음

final String[] parts = line.split("="); 
if (parts.length < 2) { 
    throw new IOException("Format error in file " + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(getFileName()) + ", line: " + line); 
} 
for (int i = 0; i < parts.length - 1; i++) { 
    map.put(parts[i], parts[parts.length - 1]); 
} 

로 변경할 수 어떻게 든이 일을해야합니다. 이지도로 잘못된 단어를 검색 할 수 있으며 올바른 단어가 될 것입니다.

(P.S는 : 나는 코드를 실행할 수 없습니다, 그래서 약간의 코딩 오류가있을 수 있습니다)

+0

감사합니다 Hons, 나는이 솔루션을 시도했지만 어떤 오류도 발생하지 않았지만 (두 개 이상의 부품 길이를 가짐) 코드가 잘못된 단어를 표시하지 않았습니다 ... 코드를 실행할 수없는 이유 LanguageTool의 출처에 포함되어있는 다른 스크립트를 호출하고 있기 때문에 그렇습니다. 그러나이 문제를 해결하는 방법을 잘 모릅니다 ... 해결책을 찾는데 도움이 될만한 것이 있습니까? 이것을 위해 시간을내어 주셔서 감사합니다. – Nathan

+1

물론 적어도 두 부분이 있어야합니다 ... 버전에서 정확히 두 개가 있고 내 버전에는 적어도 두 개가 있어야합니다. "잘못된 단어 표시"가 무슨 뜻인지는 분명치 않습니다. 위에 언급 한 행을 내가 작성한 행과 교환하고 원본 파일로 피드하면 이전과 똑같이해야합니다. 결국 그것은 RuleMatch 배열을 반환합니다. – Hons

+0

Thanks Hons, "잘못된 단어 플래그 지정"은 코드를 컴파일 한 다음이 확장 (Java 코드는 확장의 일부 임)을 사용할 때 OpenOffice에서 더 이상 확장하지 않습니다. 교체 단어를 표시합니다 (wrongword1을 쓸 때 correctword1을 사용한다고 말하지 않습니다). 나는 이전의 coherency.txt 파일을 두 단어 만 사용하여 시도해 보았으며 어떤 단어도 잘못 표시하지 않았습니다 ... 문제를 해결하는 방법을 모르겠지만 어떤 생각을 했습니까? – Nathan

0
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 




public class Test { 

     public static void main(String[] args) { 

      String txtFromFile = "Hipopotamus=hIppoPotamus=hiiippotamus Magazine=Mazagine=Masagine"; 
      String searchWord = "Masagine"; 
      Pattern searchPattern= Pattern.compile("\\s*(\\w+=)*?("+searchWord+")"); 
      Matcher m = searchPattern.matcher(txtFromFile); 
      String source = ""; 
      while(m.find()) { 
       source = m.group(); 
       System.out.println("word pairs:"+source); 
      } 
      System.out.println("correct word:"+source.split("=")[0]); 
     } 
    } 
관련 문제