亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 8 使用 Streams 算法搜索 ArrayList 失敗

Java 8 使用 Streams 算法搜索 ArrayList 失敗

一只甜甜圈 2024-01-25 10:35:51
我們正在使用 Stream 來搜索字符串的 ArrayList 字典文件已排序并包含 307107 個小寫單詞我們正在使用 findFirst 從 TextArea 中的文本中查找匹配項只要單詞拼寫錯誤超出 3 個字符 搜索有有利的結果如果拼寫錯誤的單詞是這樣的“Charriage”,則結果與匹配完全不相近明顯的目標是在不需要查看大量單詞的情況下獲得盡可能接近正確的結果這是我們正在測試的文本Tak acheive it hommaker 和 aparent as Chariage NOT ME Charriag 添加缺失的元音到 Cjarroage我們對流搜索過濾器進行了一些重大更改,并進行了合理的改進我們將編輯發布的代碼,以僅包含搜索失敗的代碼部分 在對流過濾器進行的代碼更改之后在代碼更改之前,如果searchString 在位置 1 處有一個拼寫錯誤的字符 在字典中找不到結果 新的搜索過濾器修復了這個問題我們還通過增加endsWith 的字符數量添加了更多搜索信息所以仍然失?。∪绻?searchString(拼寫錯誤的單詞)在單詞末尾缺少一個字符,并且該單詞在位置 1 到 4 之間有一個不正確的字符,則搜索失敗我們正在努力添加和刪除字符,但我們不確定這是否可行解決方案如果您想要我們將在 GitHub 上發布的完整項目,請在評論中詢問,我們將不勝感激。問題仍然是當拼寫錯誤的單詞中缺少多個字符時如何修復此搜索過濾器?經過幾個小時的免費 txt 詞典搜索后,這是最好的A 側欄事實之一,它有 115726 個長度 > 5 的單詞,并且單詞末尾有一個元音。這意味著它有 252234 個末尾沒有元音的單詞這是否意味著我們有 32% 的機會通過在 searchString 的末尾添加元音來解決問題?不是一個問題,只是一個奇怪的事實!這里是字典下載的鏈接,并將words_alpha.txt文件放在C盤上的C:/A_WORDS/words_alpha.txt"); words_alpha.txt
查看完整描述

3 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

我正在添加 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);

    }

}

自定義Word類


/**

 *

 * @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;

    }

}


查看完整回答
反對 回復 2024-01-25
?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

您只需要進一步了解詞典即可
我們確定您從詞典中得到了很多建議的單詞?
我們測試了您的代碼,有時它發現了 3000 個或更多可能的匹配項哇,
所以這是一個很大的改進。它仍然需要大量的測試,我們使用這條線進行測試,獲得了 100% 良好的結果。

Tske Charriage 到 hommaker 以及 hommake 作為 hommaer

我們擔心的是,如果拼寫者真的把這個詞弄亂了,這項改進可能會解決一定程度的拼寫錯誤。
我們確信您知道,如果第一個字母是錯誤的,這將不起作用,
就像仇外心理對仇外心理一樣

這是重大改進

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

您可以將支票發送到我的地址 55 48 196 195


查看完整回答
反對 回復 2024-01-25
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

我認為你應該使用類似于Levenshtein Distanceor的東西Jaro Winkler Distance。如果你可以使用Apache's?Commons.?我建議使用Apache Commons Lang.?它有一個實現Levenshtein Distance。該示例演示了此實現。如果將距離設置為(distance <= 2),您可能會獲得更多結果。

import java.io.File;

import java.io.IOException;

import java.net.URL;

import java.nio.charset.Charset;

import java.util.List;

import java.util.logging.Level;

import java.util.logging.Logger;

import org.apache.commons.io.FileUtils;

import org.apache.commons.lang3.StringUtils;


/**

?*

?* @author blj0011

?*/

public class Main

{


? ? public static void main(String[] args)

? ? {

? ? ? ? try {

? ? ? ? ? ? System.out.println("Hello World!");

? ? ? ? ? ? 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);

? ? ? ? ? ? }


? ? ? ? ? ? List<String> lines = FileUtils.readLines(file, Charset.forName("UTF8"));

? ? ? ? ? ? //lines.forEach(System.out::println);


? ? ? ? ? ? lines.stream().forEach(line -> {

? ? ? ? ? ? ? ? int distance = StringUtils.getLevenshteinDistance(line, "zorilta");

? ? ? ? ? ? ? ? //System.out.println(line + ": " + distance);

? ? ? ? ? ? ? ? if (distance <= 1) {

? ? ? ? ? ? ? ? ? ? System.out.println("Did you mean: " + line);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? });


? ? ? ? }

? ? ? ? catch (IOException ex) {

? ? ? ? ? ? Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

? ? ? ? }

? ? }

}

輸出距離<=1


Building JavaTestingGround 1.0

------------------------------------------------------------------------


--- exec-maven-plugin:1.5.0:exec (default-cli) @ JavaTestingGround ---

Hello World!

Did you mean: zorilla

------------------------------------------------------------------------

BUILD SUCCESS

------------------------------------------------------------------------

Total time: 1.329 s

Finished at: 2019-11-01T11:02:48-05:00

Final Memory: 7M/30M

距離 <= 2


Hello World!

Did you mean: corita

Did you mean: gorilla

Did you mean: zoril

Did you mean: zorilla

Did you mean: zorillas

Did you mean: zorille

Did you mean: zorillo

Did you mean: zorils

------------------------------------------------------------------------

BUILD SUCCESS

------------------------------------------------------------------------

Total time: 1.501 s

Finished at: 2019-11-01T14:03:33-05:00

Final Memory: 7M/34M


查看完整回答
反對 回復 2024-01-25
  • 3 回答
  • 0 關注
  • 235 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號