一:单词统计:
统计本地文件里单词的数量:
第一:要去读到这个文件,并转换成sacal里的数据结构,便于处理;
第二:要对单词进行分割,压平
第三:对单词进行映射,并分组;
第四:在组内求和;
第五:转换成List,便于排序。
最终结果就两条代码搞定,但是对于第一次写,没有其他参考,一个人想破脑袋也无法完成,因为所学到的东西当前还不系统,都没那么深入,只能边实践边摸索,边总结;用多了,自然就会了吧,即使一个函数,如果没有需求,自己就在哪儿捣腾半天,过久就好比高中大学学的知识全都还给老师了一样。
package main.count
import scala.io.Source
object CourseWordCount {
/*
* 从本地读取文件统计单词个数
* */
def main(args: Array[String]): Unit = {
val file =Source.fromFile("xxx").getLines().toBuffer// 从本地读取文件并转化成ArrayBuffer
// val file1 =file.map(_ .split(" ")) .flatten //map+flatten 把文件的按空格切分并压平
// println(file1)
// val file2 =file.flatMap(_ .split(" ")) // flatMap=map+flatten
// println(file2)
// val file3 =file2.map(x=>(x,1))// 把单词映射为元组
// println(file3)
// val file4 =file3.groupBy(_._1) //分组
// println(file4)
// val file5 =file4.map(x=>(x._1,x._2.size)) //组内求和
// println(file5)
// val file6 =file5.toList //转化成List
// println(file6)
// val wc =file6.sortBy(_._2).reverse //按倒序排列
// println(wc)
val lines1=file.flatMap(_.split(" ")).map((_,1)).groupBy(_._1).map(t=>(t._1,t._2.size)).toList.sortBy(_._2).reverse
println(lines1)
}
}
二:模拟log生成
要生成一个模拟的日日志,里面肯定是循环向文件里写东西:
第一:怎么在一个文件里写东西;
第二:写的内容各不相同,如何把这些内容拼接起来;
第三:内容怎么来产生,比如时间;地址,IP地址(怎么来实现);
通过这个实验,熟悉了文件写入和Random函数;
package com.weizonggui.WeizhongguiPrep
import java.io.{FileWriter, Writer}
import java.text.SimpleDateFormat
import java.util.Date
import scala.util.Random
/**
* Created by weizhonggui
*/
object Test2 {
private val max_records = 10
private val path = "E:/platform.txt"
private val urls = Array("http://ruozedata.com/basic.html", "http://ruozedata.com/advanced.html",
"http://ruozedata.com/teacher.html", "http://ruozedata.com/job.html")
def main(args: Array[String]): Unit = {
Creat()
System.exit(1)
}
def Creat() = {
val rand = new Random()
val writer: FileWriter = new FileWriter(path, true)
for (i <- 1 to max_records) {
val url = urls(rand.nextInt(4))
val time = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date)
val traffic = rand.nextInt(20)
writer.write(i + " " + url + " " + time + " " + traffic)
}
writer.flush()
writer.close()
}
}