在Scala中,我有一个包含一组句子的文本。
我正在尝试将此文本拆分为单个句子,如下所示:

val sentences: Array[String] = text.split(".")

但是,当我检查sentences数组时(如下面的行所示),我发现该数组为空:
println("Sentences are: " + sentences.mkString(" "))

为什么拆分未正确完成?

对于文本:
A sword is a bladed weapon intended for both cutting and thrusting. The precise definition of the term varies with the historical epoch or the geographical region under consideration. A sword in the most narrow sense consists of a straight blade with two edges.

输出为:
Sentences are:

最佳答案

String.split需要一个正则表达式,而.在正则表达式中表示“任何内容”,因此您需要对其进行转义:

val sentences: Array[String] = text.split("\\.")

现在,如果分隔符是单个字符,则可以使用重载的split(char)方法,该方法不会将参数解释为正则表达式。
val sentences: Array[String] = text.split('.')

10-06 01:01