【问题标题】:How to split an ArrayList of sentences into an ArrayList of words in Java without reading a text file more than once?java - 如何在Java中将句子的ArrayList拆分为单词的ArrayList,而无需多次读取文本文件?
【发布时间】:2018-09-02 06:31:52
【问题描述】:

我只需要读取一个文本文件一次并将句子存储到一个 ArrayList 中。然后,我需要将句子的 ArrayList 拆分为每个单词的另一个 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();
        }
    }
}

【问题讨论】:

  • 您只阅读了一次文件。为什么你认为你会不止一次地阅读它?
  • 你到底是什么意思? readLine() 不代表你阅读了整个文件。
  • 如果您想一次阅读整个文件,也许您应该看到this postThis 也很有用。
  • 感谢链接,暗淡。这些说明看起来就像你循环浏览文件一样,它会再次读取它。我不确定每个 for 循环是否都在重新读取文件。

标签: java arraylist


【解决方案1】:

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

它没有。您只是在重新分析您已经阅读的行。

你的问题已经解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2013-12-13
    • 2020-04-29
    • 2012-04-18
    • 2020-01-30
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多