簡體   English   中英

Java從文件讀取字母到多維數組

[英]Java Read alphabet from file to multi-dimensional array

首先,這絕對是一個邏輯問題,但我似乎無法解決該問題:

我有一個.txt文件,正在讀取,整個字母由1和0組成,例如,在.txt文件中,這是一個B,然后是C:

0 0 1 1 1 1 0 0 0
0 0 1 0 0 0 1 0 0
0 0 1 1 1 1 0 0 0
0 0 1 0 0 0 1 0 0
0 0 1 1 1 1 0 0 0

0 0 0 1 1 1 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0

您可以按照1來區分字母。 我需要做的是將每個字母讀入一個數組字母,每個字母用空行分隔,並且字母必須遵循這種格式。 這是一個5x9的數字矩陣,我需要將其轉換為45 x 1的數組並將其存儲在26個字母的字母數組中。

這是用於光學字符識別神經網絡的,我必須使用硬編碼數字,但是從文件中讀取數據已被證明是技巧。

這是我到目前為止的內容:

String[][] alphabet = new String[26][45];
    float [][] trainingDataFile = new float[26][45];
    int row = 0;

    Scanner file = new Scanner(new BufferedReader(new FileReader("Alphabet.txt")));
    /*
        While the file has another line, read in data until empty line. 
    */
    while(file.hasNextLine())
    {

        String line = file.nextLine();
        if(line.length() != 0)
        {
            String[] letters = line.split(" ");
            alphabet[row] = letters;

        } else {
            row++;
        }

    }

在我的腦海中,算法將去:讀入數據並追加到字符串,直到空行,然后遞增到下一個字母。

但是我不知道如何將其轉換為代碼。 我似乎無法弄清楚如何繼續讀取單個字母的塊直到空行。

  1. 該文件足夠小,可以將其加載到內存中。 Java 7 nio有一個單行方法可以做到這一點。

  2. 使用List比使用數組要容易得多,因為它們會隨着插入數據而自動增長。 您可以根據需要將數組轉換為列表,反之亦然。

這是我的解決方案:

    String[][] alphabet = new String[26][45];

    try {
        // read the entire file into memory
        List<String> lines = Files.readAllLines(Paths.get("C://temp/xx.txt"));
        // this will hold 45x1 array as list
        List<String> concatenated = new ArrayList<>();
        int row = 0;
        for (String line : lines) {
            if (line.isEmpty()) {
                // convert list to array and add to matrix
                alphabet[row] = concatenated.toArray(alphabet[row]);
                concatenated = new ArrayList<>();
                row++;
            } else {
                // convert result of split() to list and add to letter list
                concatenated.addAll(Arrays.asList(line.split(" ")));
            }
        }
        // take care of last letter
        alphabet[row] = concatenated.toArray(alphabet[row]);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Arrays.stream(alphabet).forEach(row -> System.out.println(Arrays.toString(row)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM