这绝对是首要的逻辑问题,但我似乎无法解决该问题:
我有一个.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++;
}
}
在我的脑海中,算法将运行: 读入数据并追加到字符串,直到空行,然后递增到下一个字母。
但是我不知道如何将其转换为代码。 我似乎无法弄清楚如何继续读取单个字母的块直到空行。
答案 0 :(得分:2)
文件足够小,可以将其加载到内存中。 Java 7 nio
具有实现此目的的单行方法。
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)));
}