我有一个从 URL 读取并使用分隔符将文本分割成句子的方法。这是我所拥有的:
try {
URL url = new URL("Some link");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String l;
while((l = in.readLine()) != null) {
String sentence = l.replaceAll("[^a-zA-Z?.!]"," ");
String[] sent = sentence.split("[?.!]", 2);
for(int x = 0; x < sent.length; x++) {
System.out.println(sent[x]);
}
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
这将逐句打印出文本。然而,我想一次读 30 个句子,只是想知道我会如何去做。
最佳答案
首先使用 StringBuilder 连接整个文本,然后用一个点将其分割,最后循环 50 次,打印整个文本数组的 50 个第一个索引。
StringBuilder sb = new StringBuilder();
while((l = in.readLine()) != null) {
sb.append(l);
}
String[] sentences = sb.toString().split(".");
for (int i = 0 ; i < 50 ; i++){
System.out.println(sentences[i]);
}
关于java - 在 Java 中打印句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467965/