gpt4 book ai didi

java - 从文件读取时省略所有空行

转载 作者:行者123 更新时间:2023-12-01 17:18:07 25 4
gpt4 key购买 nike

我目前正在尝试获取大文本并逐句分割文本。我有代码将文本分割成单独的句子,但它当然也包括空格。我需要在代码中添加什么才能使其省略句子数组中的空格?

    String [] sentence
ArrayList <String> sentenceList = new ArrayList <String> ();
try {
Scanner sentenceScanner = new Scanner (new File("data/" + fileName));
while (sentenceScanner.hasNextLine()) {
sentenceList.add (sentenceScanner.nextLine());
}
sentenceScanner.close();
} catch (FileNotFoundException e) {
System.out.println ("File Not Found");
}

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]);
}
}

最佳答案

最好在读取输入数据时进行过滤:

while (sentenceScanner.hasNextLine()) {
String line = sentenceScanner.nextLine().trim();
if (!line.isEmpty()) {
sentenceList.add (line);
}
}

关于java - 从文件读取时省略所有空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61347433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com