如何将 csv 文件中的每个单词放入二维数组中的句子中

How to put each word in a sentence inside a 2d array from a csv file

我正在尝试读取一个文本文件并将每个逗号分隔值放入一个数组中,然后将它们全部放入一个 2d array.But 我现在拥有的代码将整行放入数组中

Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
        int rows = 3;
        int columns = 1;
        String[][] myArray = new String[rows][columns];
        while (sc.hasNextLine()) {
            for (int i = 0; i < myArray.length; i++) {
                String[] line = sc.nextLine().trim().split(" " + ",");
                for (int j = 0; j < line.length; j++) {
                    myArray[i][j] = line[j];
                }
            }
        }
        System.out.println(Arrays.deepToString(myArray));

这是文本文件:

A6,A7
F2,F3
F6,G6

输出

[[A6,A7], [F2,F3], [F6,G6]]

预期输出

[[A6],[A7],[F2],[F3],[F6],[G6]]

我认为你必须将行的大小加倍,并且对于每一行只需放置一个元素并增加 i++

问题是您分配的是整个二维数组,而不是每个项目。

这里有几种选择。

  • 使用 Files.lines 流式传输文件。
  • 以逗号分隔为每行创建两个元素的一维数组
  • flatMap 流式传输每个项目。
  • that map that 到一个包含一项的数组。
  • 然后将它们存储在二维数组中。
String[][] array = null;
try {
    array = Files.lines(Path.of("f:/MyInfo.txt"))
            .flatMap(line->Arrays.stream(line.split(","))
                 .map(item->new String[]{item}))
            .toArray(String[][]::new);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
if (array != null) {
    System.out.println(Arrays.deepToString(array));
}

打印

[[A6], [A7], [F2], [F3], [F6], [G6]]

这里有一个类似于你的方法。

List<String[]> list = new ArrayList<>();
try {
    Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
    while (scanner.hasNextLine()) {
        String[] arr = scanner.nextLine().split(",");
        for (String item : arr) {
            list.add(new String[]{item});
        }
    }
} catch (IOException ioe) {
    ioe.printStackTrace();
}

Lists 没有 deepToString,因此您要么对其进行迭代,要么将其转换为二维数组。

String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));

打印

[[A6], [A7], [F2], [F3], [F6], [G6]]

结果数组的声明不正确。

因为你希望最终结果应该是这样的,[[A6],[A7],[F2],[F3],[F6],[G6]],它是一个二维数组,1行6列。

考虑到这一点,我已经更改并简化了您的代码。

int rows = 3;
String[][] r = new String[1][rows * 2];

FileInputStream fstream = new FileInputStream("/path/to/the/file") 
BufferedReader br = new BufferedReader(new InputStreamReader(stream));

while((line = br.readLine()) != null) {
    String[] current = line.split(",");
    r[0][i++] = current[0];
    r[0][i++] = current[1];
}