Streams 알고리즘이있는 Java 8 검색 ArrayList 실패

벡터

우리는 Stream을 사용하여 문자열의 ArrayList를 검색하고 있습니다. Dictionary 파일은 정렬되어 있으며 모두 소문자로 된 307107 개의 단어를 포함합니다.
우리는 TextArea의 텍스트에서 일치
하는 단어 를 찾기 위해 findFirst를 사용합니다. 문자 검색에 유리한 결과
가 있습니다 철자가 잘못된 단어가이 "Charriage"와 같으면 결과는 일치에 가깝지 않습니다
. 명백한 목표는 막대한 수의 단어를 보지 않고도 정확한 결과 를 얻는 것입니다.

다음은
Chariage NOT ME Charriag가 Cjarroage에 누락 된 모음을 추가하는 것처럼 Tak이 동성애자 및 부모를 사용하는 텍스트입니다.

합리적인 개선을 통해 스트림 검색 필터에 몇 가지 주요 변경 사항을 적용했습니다.
검색이 실패한 코드의 일부만 포함하도록 게시 된 코드를 편집하고
그 아래에서 스트림 필터에
대한 코드 변경 사항을 수정합니다. searchString의 위치 1에 잘못된 문자가 있습니다. 사전에서 결과를 찾을 수 없습니다. 새로운 검색 필터가 수정
되었습니다. 우리는 또한 endWith에 대한 문자 수를 늘려서 더 많은 검색 정보를 추가했습니다.
그래서 여전히 실패한 것은 무엇입니까! searchString (맞춤법이 잘못된 단어)에 단어 끝에 문자가없고 단어에 위치 1에서 4까지 잘못된 문자가 있으면 검색이 실패합니다.
문자를 추가 및 제거하는 중이지만 이것이 실행 가능한지 확실하지 않습니다. 해결책

GitHub에 게시 할 전체 프로젝트를 원하시면 의견이나 코드를 보내 주시면 대단히 감사하겠습니다.

문제는 맞춤법이 틀린 단어에서 여러 문자가 누락 된 경우이 검색 필터를 수정하는 방법입니다.

무료 txt 사전을 여러 시간 검색 한 후 이것은
길이가 5 개를 초과하고 단어 끝에 모음이있는 115726 개의 단어가 있다는 최고의 A 사이드 바 사실 중 하나입니다 . 즉, 끝에 모음이없는 252234 개의 단어가
있음을 의미합니다. searchString 끝에 모음을 추가하여 문제를 해결할 가능성이 32 %라는 의미입니까? 질문이 아니라 이상한 사실입니다!

여기에 사전 다운로드 링크가 있으며 C : /A_WORDS/words_alpha.txt "의 C 드라이브에 words_alpha.txt 파일을 배치하십시오. words_alpha.txt

변경 전 코드

}if(found != true){

    lvListView.setStyle("-fx-font-size:18.0;-fx-background-color: white;-fx-font-weight:bold;");
    for(int indexSC = 0; indexSC < simpleArray.length;indexSC++){

    String NewSS = txtMonitor.getText().toLowerCase();

    if(NewSS.contains(" ")||(NewSS.matches("[%&/0-9]"))){
        String NOT = txtMonitor.getText().toLowerCase();
        txtTest.setText(NOT+" Not in Dictionary");
        txaML.appendText(NOT+" Not in Dictionary");
        onCheckSpelling();
        return;
    }

    int a = NewSS.length();
    int Z;
    if(a == 0){// manage CR test with two CR's
        Z = 0;
    }else if(a == 3){
        Z = 3;
    }else if(a > 3 && a < 5){
        Z = 4;
    }else if(a >= 5 && a < 8){
        Z = 4;
    }else{
        Z = 5;
    }

    System.out.println("!!!! NewSS "+NewSS+" a "+a+" ZZ "+Z);

    if(Z == 0){// Manage CR in TextArea
        noClose = true;
        strSF = "AA";
        String NOT = txtMonitor.getText().toLowerCase();
        //txtTo.setText("Word NOT in Dictionary");// DO NO SEARCH
        //txtTest.setText("Word NOT in Dictionaary");
        txtTest.setText("Just a Space");
        onCheckSpelling();   
    }else{
        txtTest.setText("");
        txaML.clear();
        txtTest.setText("Word NOT in Dictionaary");
        txaML.appendText("Word NOT in Dictionaary");
        String strS = searchString.substring(0,Z).toLowerCase();
        strSF = strS; 
    }
    // array & list use in stream to add results to ComboBox
    List<String> cs = Arrays.asList(simpleArray);
    ArrayList<String> list = new ArrayList<>();

    cs.stream().filter(s -> s.startsWith(strSF))
      //.forEach(System.out::println); 
    .forEach(list :: add);   

    for(int X = 0; X < list.size();X++){
    String A = (String) list.get(X);  

개선 된 새 코드

        }if(found != true){

    for(int indexSC = 0; indexSC < simpleArray.length;indexSC++){

    String NewSS = txtMonitor.getText().toLowerCase();
    if(NewSS.contains(" ")||(NewSS.matches("[%&/0-9]"))){
        String NOT = txtMonitor.getText().toLowerCase();
        txtTest.setText(NOT+" Not in Dictionary");

        onCheckSpelling();
        return;
    }
    int a = NewSS.length();
    int Z;
    if(a == 0){// manage CR test with two CR's
        Z = 0;
    }else if(a == 3){
        Z = 3;
    }else if(a > 3 && a < 5){
        Z = 4;
    }else if(a >= 5 && a < 8){
        Z = 4;
    }else{
        Z = 5;
    }

    if(Z == 0){// Manage CR
        noClose = true;
        strSF = "AA";
        String NOT = txtMonitor.getText().toLowerCase();
        txtTest.setText("Just a Space");
        onCheckSpelling();

    }else{
        txtTest.setText("");
        txtTest.setText("Word NOT in Dictionaary");
        String strS = searchString.substring(0,Z).toLowerCase();
        strSF = strS; 
    }
    ArrayList list = new ArrayList<>(); 
    List<String> cs = Arrays.asList(simpleArray);
    // array list & list used in stream foreach filter results added to ComboBox
    // Code below provides variables for refined search
    int W = txtMonitor.getText().length();

    String nF = txtMonitor.getText().substring(0, 1).toLowerCase();

    String nE = txtMonitor.getText().substring(W - 2, W);
    if(W > 7){
    nM = txtMonitor.getText().substring(W-5, W);
    System.out.println("%%%%%%%% nE "+nE+" nF "+nF+" nM = "+nM);
    }else{
    nM = txtMonitor.getText().substring(W-1, W);   
    System.out.println("%%%%%%%% nE "+nE+" nF "+nF+" nM = "+nM);
    }

    cs.stream().filter(s -> s.startsWith(strSF)
            || s.startsWith(nF, 0)
            && s.length()<= W+2
            && s.endsWith(nE)
            && s.startsWith(nF)
            && s.contains(nM)) 
    .forEach(list :: add);

    for(int X = 0; X < list.size();X++){
    String A = (String) list.get(X);
    sort(list);

    cboSelect.setStyle("-fx-font-weight:bold;-fx-font-size:18.0;");
    cboSelect.getItems().add(A);
    }// Add search results to cboSelect
    break;

다음은 컨트롤 이름이 ComboBox를 제외하고 코드에 사용 된 이름과 동일한 FXML 파일의 스크린 샷입니다.
FXML 레이아웃

세드릭

JavaFX 답변을 추가하고 있습니다. 이 앱은 Levenshtein Distance. Check Spelling시작하려면를 클릭 해야합니다. 목록에서 단어를 선택하여 현재 검사중인 단어를 바꿀 수 있습니다. 나는 알 Levenshtein Distance당신이 더 많은 목록을 아래로 줄일 수있는 다른 방법을 모색 할 수 있도록 단어의 반환을 많이.

본관

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class App extends Application
{

    public static void main(String[] args)
    {
        launch(args);
    }

    TextArea taWords = new TextArea("Tak Carrage thiss on hoemaker answe");
    TextField tfCurrentWordBeingChecked = new TextField();
    //TextField tfMisspelledWord = new TextField();
    ListView<String> lvReplacementWords = new ListView();
    TextField tfReplacementWord = new TextField();

    Button btnCheckSpelling = new Button("Check Spelling");
    Button btnReplaceWord = new Button("Replace Word");

    List<String> wordList = new ArrayList();
    List<String> returnList = new ArrayList();
    HandleLevenshteinDistance handleLevenshteinDistance = new HandleLevenshteinDistance();
    ObservableList<String> listViewData = FXCollections.observableArrayList();

    @Override
    public void start(Stage primaryStage)
    {
        setupListView();
        handleBtnCheckSpelling();
        handleBtnReplaceWord();

        VBox root = new VBox(taWords, tfCurrentWordBeingChecked, lvReplacementWords, tfReplacementWord, btnCheckSpelling, btnReplaceWord);
        root.setSpacing(5);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void handleBtnCheckSpelling()
    {
        btnCheckSpelling.setOnAction(actionEvent -> {
            if (btnCheckSpelling.getText().equals("Check Spelling")) {
                wordList = new ArrayList(Arrays.asList(taWords.getText().split(" ")));
                returnList = new ArrayList(Arrays.asList(taWords.getText().split(" ")));
                loadWord();
                btnCheckSpelling.setText("Check Next Word");
            }
            else if (btnCheckSpelling.getText().equals("Check Next Word")) {
                loadWord();
            }
        });
    }

    public void handleBtnReplaceWord()
    {
        btnReplaceWord.setOnAction(actionEvent -> {
            int indexOfWordToReplace = returnList.indexOf(tfCurrentWordBeingChecked.getText());
            returnList.set(indexOfWordToReplace, tfReplacementWord.getText());
            taWords.setText(String.join(" ", returnList));
            btnCheckSpelling.fire();
        });
    }

    public void setupListView()
    {
        lvReplacementWords.setItems(listViewData);
        lvReplacementWords.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
            tfReplacementWord.setText(newSelection);
        });
    }

    private void loadWord()
    {
        if (wordList.size() > 0) {
            tfCurrentWordBeingChecked.setText(wordList.get(0));
            wordList.remove(0);
            showPotentialCorrectSpellings();
        }
    }

    private void showPotentialCorrectSpellings()
    {
        List<String> potentialCorrentSpellings = handleLevenshteinDistance.getPotentialCorretSpellings(tfCurrentWordBeingChecked.getText().trim());
        listViewData.setAll(potentialCorrentSpellings);
    }
}

CustomWord 클래스

/**
 *
 * @author blj0011
 */
public class CustomWord
{

    private int distance;
    private String word;

    public CustomWord(int distance, String word)
    {
        this.distance = distance;
        this.word = word;
    }

    public String getWord()
    {
        return word;
    }

    public void setWord(String word)
    {
        this.word = word;
    }

    public int getDistance()
    {
        return distance;
    }

    public void setDistance(int distance)
    {
        this.distance = distance;
    }

    @Override
    public String toString()
    {
        return "CustomWord{" + "distance=" + distance + ", word=" + word + '}';
    }
}

HandleLevenshteinDistance 클래스

/**
 *
 * @author blj0011
 */
public class HandleLevenshteinDistance
{

    private List<String> dictionary = new ArrayList<>();

    public HandleLevenshteinDistance()
    {
        try {
            //Load DictionaryFrom file
            //See if the dictionary file exists. If it don't download it from Github.
            File file = new File("alpha.txt");
            if (!file.exists()) {
                FileUtils.copyURLToFile(
                        new URL("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt"),
                        new File("alpha.txt"),
                        5000,
                        5000);
            }

            //Load file content to a List of Strings
            dictionary = FileUtils.readLines(file, Charset.forName("UTF8"));
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public List<String> getPotentialCorretSpellings(String misspelledWord)
    {
        LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
        List<CustomWord> customWords = new ArrayList();

        dictionary.stream().forEach((wordInDictionary) -> {
            int distance = levenshteinDistance.apply(misspelledWord, wordInDictionary);
            if (distance <= 2) {
                customWords.add(new CustomWord(distance, wordInDictionary));
            }
        });

        Collections.sort(customWords, (CustomWord o1, CustomWord o2) -> o1.getDistance() - o2.getDistance());

        List<String> returnList = new ArrayList();
        customWords.forEach((item) -> {
            System.out.println(item.getDistance() + " - " + item.getWord());
            returnList.add(item.getWord());
        });

        return returnList;
    }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

ArrayList를 검색하는 java.lang.NullPointerException

분류에서Dev

BeautifulSoup이 Java 생성 HTML로 실패하는 태그 검색

분류에서Dev

JS 트리 검색 실패

분류에서Dev

Java에서 ArrayList 검색

분류에서Dev

8 진 검색 알고리즘으로 성능 향상

분류에서Dev

Java mergesort 알고리즘이 때때로 실패하는 이유를 모르겠습니다.

분류에서Dev

Java : 검색시 ArrayList 항목이 반환되지 않음

분류에서Dev

Java-Arraylist를 통한 재귀 이진 검색

분류에서Dev

Java-Arraylist를 통한 재귀 이진 검색

분류에서Dev

빠른 공간 검색 알고리즘 / 패키지

분류에서Dev

JAVA ArrayList는 ArrayList 메소드에서 모든 객체를 검색합니다.

분류에서Dev

쿼리 검색에서 Azure Bing 웹 검색이 실패 함

분류에서Dev

내 힙의 알고리즘 구현이 실패하는 Java List 관련 미묘함은 무엇입니까?

분류에서Dev

Java Streams를 사용하여 복잡한 데이터 구조에서 검색

분류에서Dev

MySQL 검색 알고리즘

분류에서Dev

배열에서 단어를 검색하는 알고리즘이 있습니까?

분류에서Dev

이진 검색 알고리즘

분류에서Dev

이진 검색 답 알고리즘

분류에서Dev

이진 검색 알고리즘-Python

분류에서Dev

이진 검색 트리 및 정렬 (및 기타 기본 알고리즘), C # 및 Java로 작성된 코드는 거의 상호 교환이 가능합니까?

분류에서Dev

Arraylist에서 특정 요소를 어떻게 검색 할 수 있습니까? (java)

분류에서Dev

"indexOf"가있는 검색 문자열이 실패합니다.

분류에서Dev

Java 8 Streams int 및 Integer

분류에서Dev

Java 8 Streams modify collection values

분류에서Dev

Using Java 8 Streams for hiearchy of classes

분류에서Dev

Java 8 Streams — 매핑 맵

분류에서Dev

Java 실행 파일 검색

분류에서Dev

Android Bluetooth : java.io.IOException : 서비스 검색 실패

분류에서Dev

새로운 에지로 실행되는 새로운 DFS에서 동일한 검색 / 종료 시간이 가능한지 결정하는 알고리즘 설명

Related 관련 기사

  1. 1

    ArrayList를 검색하는 java.lang.NullPointerException

  2. 2

    BeautifulSoup이 Java 생성 HTML로 실패하는 태그 검색

  3. 3

    JS 트리 검색 실패

  4. 4

    Java에서 ArrayList 검색

  5. 5

    8 진 검색 알고리즘으로 성능 향상

  6. 6

    Java mergesort 알고리즘이 때때로 실패하는 이유를 모르겠습니다.

  7. 7

    Java : 검색시 ArrayList 항목이 반환되지 않음

  8. 8

    Java-Arraylist를 통한 재귀 이진 검색

  9. 9

    Java-Arraylist를 통한 재귀 이진 검색

  10. 10

    빠른 공간 검색 알고리즘 / 패키지

  11. 11

    JAVA ArrayList는 ArrayList 메소드에서 모든 객체를 검색합니다.

  12. 12

    쿼리 검색에서 Azure Bing 웹 검색이 실패 함

  13. 13

    내 힙의 알고리즘 구현이 실패하는 Java List 관련 미묘함은 무엇입니까?

  14. 14

    Java Streams를 사용하여 복잡한 데이터 구조에서 검색

  15. 15

    MySQL 검색 알고리즘

  16. 16

    배열에서 단어를 검색하는 알고리즘이 있습니까?

  17. 17

    이진 검색 알고리즘

  18. 18

    이진 검색 답 알고리즘

  19. 19

    이진 검색 알고리즘-Python

  20. 20

    이진 검색 트리 및 정렬 (및 기타 기본 알고리즘), C # 및 Java로 작성된 코드는 거의 상호 교환이 가능합니까?

  21. 21

    Arraylist에서 특정 요소를 어떻게 검색 할 수 있습니까? (java)

  22. 22

    "indexOf"가있는 검색 문자열이 실패합니다.

  23. 23

    Java 8 Streams int 및 Integer

  24. 24

    Java 8 Streams modify collection values

  25. 25

    Using Java 8 Streams for hiearchy of classes

  26. 26

    Java 8 Streams — 매핑 맵

  27. 27

    Java 실행 파일 검색

  28. 28

    Android Bluetooth : java.io.IOException : 서비스 검색 실패

  29. 29

    새로운 에지로 실행되는 새로운 DFS에서 동일한 검색 / 종료 시간이 가능한지 결정하는 알고리즘 설명

뜨겁다태그

보관