【问题标题】:Java Scanner Split Strings by SentencesJava Scanner 按句子拆分字符串
【发布时间】:2014-01-25 01:50:06
【问题描述】:

我正在尝试根据标点符号将一段文本拆分为单独的句子,即 [.?!] 但是,即使我指定了特定的,扫描仪也会在每个新行的末尾拆分行图案。我该如何解决这个问题?谢谢!

this is a text file. yes the
deliminator works
no it does not. why not?

Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
  line = scanner.next();
  System.out.println(line);
}

【问题讨论】:

  • 新行在您的代码中,因此它也在行尾分隔。从您的输入中删除新行。

标签: java regex java.util.scanner


【解决方案1】:

我不相信扫描仪会在换行符处将其拆分,只是您的“行”变量中有换行符,这就是您获得该输出的原因。例如,您可以将这些换行符替换为空格:

(我正在读取您从文件中提供的相同输入文本,因此它有一些额外的文件读取代码,但您会得到图片。)

try {
    File file = new File("assets/test.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter("[.?!]");
    while (scanner.hasNext()) {
        String sentence = scanner.next();
        sentence = sentence.replaceAll("\\r?\\n", " ");
        // uncomment for nicer output
        //line = line.trim();
        System.out.println(sentence);
    }
    scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

这是结果:

this is a text file
 yes the deliminator works no it does not
 why not

如果我取消注释修剪线,它会更好一点:

this is a text file
yes the deliminator works no it does not
why not

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多