加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala地图字数?

发布时间:2020-12-16 09:08:15 所属栏目:安全 来源:网络整理
导读:此问题出现在 Scala for the Impatient中的“地图和元组”章节下 Write a program that reads words from a file. Use a mutable map to count how often each word appears. 我的尝试是 // source file: https://www.gutenberg.org/cache/epub/35709/pg3570
此问题出现在 Scala for the Impatient中的“地图和元组”章节下

  1. Write a program that reads words from a file. Use a mutable map to count how often each word appears.

我的尝试是

// source file: https://www.gutenberg.org/cache/epub/35709/pg35709.txt 
scala> val words = scala.io.Source.fromFile("pg35709.txt").mkString.split("s+")
words: Array[String] = Array(?The,Project,Gutenberg,EBook,of,Making,Your,Camera,Pay,by,Frederick,C.,Davis,This,eBook,is,for,the,use,anyone,anywhere,at,no,cost,and,with,almost,restrictions,whatsoever.,You,may,copy,it,give,away,or,re-use,under,terms,License,included,this,online,www.gutenberg.net,Title:,Author:,Release,Date:,March,29,2011,[EBook,#35709],Language:,English,***,START,OF,THIS,PROJECT,GUTENBERG,EBOOK,MAKING,YOUR,CAMERA,PAY,Produced,The,Online,Distributed,Proofreading,Team,http://www.pgdp.net,(This,file,was,produced,from,images,generously,made,available,In... 

scala> val wordCount = scala.collection.mutable.HashMap[String,Int]()
wordCount: scala.collection.mutable.HashMap[String,Int] = Map()

scala> for (word <- words) {
     | val count = wordCount.getOrElse(word,0)
     | wordCount(word) = count + 1
     | }

scala> word
wordCount   words

scala> wordCount
res1: scala.collection.mutable.HashMap[String,Int] = Map(arts -> 1,follow -> 3,request,-> 1,Lines. -> 1,demand -> 7,1.E.4. -> 1,PRODUCT -> 2,470 -> 1,Chicago,-> 3,scenic -> 1,J2 -> 1,untrimmed -> 1,photographs--not -> 1,basis. -> 1,"prints -> 1,instances. -> 1,Onion-Planter -> 1,trick -> 1,illustrating -> 3,prefer. -> 1,detected -> 1,non-exclusive. -> 1,famous -> 1,Competition -> 2,expense -> 1,created -> 2,renamed. -> 1,maggot -> 1,calendar-photographs,widely-read -> 1,Publisher,producers -> 1,Shapes -> 1,ARTICLES -> 2,yearly -> 2,retoucher -> 1,satisfy -> 2,agrees: -> 1,Gentleman_,intellectual -> 2,hard -> 2,Porch. -> 1,sold.) -> 1,START -> 1,House -> 2,welcome -> 1,Dealers' -> 1,... -> 2,pasted -> 1,_Cosmopolitan_ -...

虽然我知道这有效,但我想知道Scalaesque是否有实现这一目标的方法

解决方法

你可以这样做:

val wordCount = words.groupBy(w => w).mapValues(_.size)

groupBy方法将给定函数的结果中的映射返回到从函数返回相同值的值集合.在这种情况下,Map [String,Array [String]].然后mapValues将Array [String]映射到它们的长度.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读