TiAmo123yy 2023-03-10 16:35 采纳率: 50%
浏览 51
已结题

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

  • 写回答

2条回答 默认 最新

  • chenshanshan128 2023-03-10 17:16
    关注

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

    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.
    
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月19日
  • 已采纳回答 3月11日
  • 创建了问题 3月10日