scala程序统计单词次数

求帮忙解答一下,刚学这个,还不太懂,希望能够帮忙解答一下

  1. 给定一段英文如下:
    Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI.
    编写scala程序判断文中Spark一词出现过几次,输出这个数字。
    (提示:可将文字直接赋值给字符串,也可以存入文本文件读进来)

img

将文本赋值给一个字符串变量,比如:

val text = "Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI."

使用字符串的 count 方法来计算 "Spark" 出现的次数,比如:

val count = text.split("Spark").length - 1

这里使用了字符串的 split 方法将字符串按照 "Spark" 分割成多个子串,然后计算子串个数减去 1 就是 "Spark" 出现的次数。

输出结果,比如:

println(s""""Spark" occurs $count times in the text.""")

完整的程序如下:

object Main extends App {
  val text = "Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI."
  val count = text.split("Spark").length - 1
  println(s""""Spark" occurs $count times in the text.""")
}

输出结果为:

"Spark" occurs 4 times in the text.

希望这个回答能够帮到您!

https://blog.csdn.net/qq_44884269/article/details/89520994