![](/img/trans.png)
[英]Split ArrayList of sentences into words, store the words into new ArrayList
[英]How to split an ArrayList of sentences into an ArrayList of words in Java without reading a text file more than once?
我需要閱讀的文本文件只有一次,句子存儲到一個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();
}
}
}
/*Not sure if the code below reads the file again. If it does, then it is useless.*/
它沒有。 您只是在重新解析您已經閱讀過的行。
你已經解決了你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.