0

我有点学习 android...我想知道是否有办法从 android User Dictionary 类中随机访问 3 个字母词或 4 个字母词或某些特定类型的词??考虑到 android有一个自动更正的功能我猜它里面也有一本字典……因此我该如何使用它……我在哪里可以找到合适的教程?

我对代码一无所知...搜索了很多...请帮助我提供代码以及可能的解释:)

4

1 回答 1

1

我不知道如何访问 android 字典,但您可以在应用程序的资产文件夹中将“自定义”字典作为 txt 文件。这个链接有几个单词列表,从大约 20,000 个单词到 200,000 个单词。您可以通过 google 找到更多列表。

之后,您可以读取 txt 文件并将其添加到数组列表(如果它与字长匹配)。然后可以从字典列表中选择一个随机词。以下代码将创建字典并从中选择一个随机单词。

private ArrayList<String> dictionary;
private int wordLength; //Set elsewhere

private void createDictionary(){
    dictionary = new ArrayList<String>();

    BufferedReader dict = null; //Holds the dictionary file
    AssetManager am = this.getAssets();

    try {
        //dictionary.txt should be in the assets folder.
        dict = new BufferedReader(new InputStreamReader(am.open("dictionary.txt")));

        String word;
        while((word = dict.readLine()) != null){
            if(word.length() == wordLength){
                dictionary.add(word);
            }
        }

     } catch (FileNotFoundException e){
         e.printStackTrace();
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

    try {
        dict.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

//Precondition: the dictionary has been created.
private String getRandomWord(){
    return dictionaryList.get((int)(Math.random() * dictionaryList.size()));
}
于 2013-08-28T17:11:44.960 回答