我有一段代码可以从文本文件中读取并将每个句子存储到一个数组中。这是代码:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld{
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/input7.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[0]);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
}
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
这是input7.txt中的内容
Shocking images of a Taiwan apartment complex felled like a tree by an earthquake have highlighted what is needed to build a structure that can withstand seismic shocks.
Like Taiwan, Japan is quake-prone -- it suffers about a fifth of the world’s most powerful tremors. It has used a mix of ancient and modern technologies to make its buildings increasingly quake-proof.
Lessons have been consistently learnt and building standards subsequently raised in the wake of deadly disasters such as the 1995 Kobe earthquake, which killed 6,434 people.
When a massive magnitude earthquake struck off northeastern Japan on March 11, 2011, the shaking in Tokyo was violent. But buildings -- including the nearly complete 634-metre (2,080 feet) Tokyo Skytree tower and other skyscrapers -- survived intact.
但是,代码只会读入并显示文件最后一行的句子:
Sentence 1: When a massive magnitude earthquake struck off northeastern Japan on March 11, 2011, the shaking in Tokyo was violent.
Sentence 2: But buildings -- including the nearly complete 634-metre (2,080 feet) Tokyo Skytree tower and other skyscrapers -- survived intact.
任何人都知道如何让程序显示文件中从行首到最后的所有句子?谢谢!
最佳答案
一种方法是:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/input7.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*");
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
在第一个 for 循环中添加第二个 for 循环应该有帮助 :) !
关于Java从文本文件中读取和拆分句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35267533/