前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WordsCount

WordsCount

作者头像
用户1733462
发布2018-06-01 17:30:53
4090
发布2018-06-01 17:30:53
举报
文章被收录于专栏:数据处理数据处理

这个例子还是蛮具有代表性的,主要练习访问文件读取文件,Map键值对使用,foreach遍历,匿名函数

代码语言:javascript
复制
import java.io.File
import scala.io.Source

class WordsCount{
  def subdirs(dir: File): Iterator[File] = {
    val children = dir.listFiles.filter(_.isFile)
    children.toIterator
  }

  def getWordNum(file: Iterator[File]):scala.collection.mutable.Map[String, Int]={
    val wordsMap = scala.collection.mutable.Map[String, Int]()
      file.foreach(file => Source.fromFile(file).getLines().foreach(line=>line.split(" ").foreach(
        word=>{
          if (wordsMap.contains(word)){
            wordsMap(word)+=1
          }
          else{
            wordsMap(word)=1
          }
        }
      )))
    wordsMap
  }

}
object WordCount {
  def main(args: Array[String]): Unit = {
    val wc = new WordsCount()
    val dir = new File("E:\\scala")
    val wordsMap = wc.getWordNum(wc.subdirs(dir))
    for ((k, v) <- wordsMap)
    {
      println(k+":"+v)
    }
  }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.12.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档