有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,如何在不多次读取文本文件的情况下将句子数组列表拆分为单词数组列表?

我只需要阅读一次文本文件,然后将句子存储到ArrayList中。然后,我需要将句子的数组列表拆分为每个单词的另一个数组列表。不知道该怎么做

在我的代码中,我已将所有单词拆分为一个ArrayList,但我认为它再次从文件中读取,这是我无法做到的

到目前为止,我的代码是:

public class Main {
    public static void main(String[] args){
        try{
            FileReader fr = new FileReader("input.txt");
            BufferedReader br = new BufferedReader(fr);
            ArrayList<String> sentences = new ArrayList<String>();
            ArrayList<String> words = new ArrayList<String>();

            String line;
            while((line=br.readLine()) != null){
                String[] lines = line.toLowerCase().split("\\n|[.?!]\\s*");
                for (String split_sentences : lines){
                    sentences.add(split_sentences);
                }
               /*Not sure if the code below reads the file again. If it
                 does, then it is useless.*/
                String[] each_word = line.toLowerCase().split("\\n|[.?!]\\s*|\\s");
                for(String split_words : each_word){
                    words.add(split_words);
                }
            }
            fr.close();
            br.close();

            String[] sentenceArray = sentences.toArray(new String[sentences.size()]);
            String[] wordArray = words.toArray(new String[words.size()]);  
         }
         catch(IOException e) {
         e.printStackTrace();
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    /*Not sure if the code below reads the file again. If it does, then it is useless.*/

    事实并非如此。你只是在重新排列你已经读过的那一行

    你已经解决了你的问题