快学scala 第九章 文件和正则表达式 读书笔记及习题答案代码

chapter 9 文件和正则表达式

标签:快学scala


一、笔记

  1. 读取文件的所有行,可以调用scala.io.Source对象的getLines方法:
 
 
  1. import scala.io.Source
  2. val source = Source.fromFile("test.txt", "UTF-8")
  3. val lineIterator = source.getLines
  4. //for(i <- lineIterator)println(i)
  5. val lines = source.getLines.toArray
  6. lines.foreach(println(_))
  7. source.close() //记得关闭Source对象
  1. 读取单个字符,直接把Source当做迭代器,因为Source类扩展自Iterator[Char].
 
 
  1. for(c <- source) ...
 
 
  1. import scala.io.Source
  2. val source = Source.fromFile("test.txt", "UTF-8").mkString
  3. val tokens = source.split("\\s+")
  4. val numbers = tokens.map(_.toString)
  5. numbers.foreach(println(_))
  1. 写入文本文件:
 
 
  1. import java.io.PrintWriter
  2. val out = new PrintWriter("test.txt")
  3. for(i <- 1 to 100) out.print(i)
  4. out.close()
  1. 访问并遍历文件目录,访问所有的子目录
 
 
  1. import java.io.File
  2. def subdirs(dir: File): Iterator[File] = {
  3. val children = dir.listFiles.filter(_.isDirectory)
  4. children.toIterator ++ children.toIterator.flatMap(subdirs _)
  5. }
  6. for(d <- subdirs(dir))
  1. 进程控制
 
 
  1. scala> import sys.process._
  2. import sys.process._
  3. scala> "ls -al .." ! //!操作符返回的结果时被执行程序的返回值

如果需要在不同的目录下运行进程,或者使用不同的环境变量,使用Process的apply方法来构造ProcessBuilder,给出命令和起始目录,以及一串对偶来设置换进变量。 
6. scala.util.matching.Regex类用于正则表达式,构造Regex对象,用String类的r方法。

 
 
  1. val numPattern = "[0-9]+".r
  2. val wsnumwsPattern = """\s+[0-9]+\s+""".r //包含反斜杠或引号
  3. for(matchString <- numPattern,findAllIn("99 bottles, 98 bottles")) 处理matchString //遍历所有匹配项的迭代器
  4. scala> numPattern.replaceFirstIn("99 bottles, 98 bottles", "XX")
  5. res9: String = XX bottles, 98 bottles

二、习题答案

9.1 编写一小段Scala代码,将某个文件中的行倒转顺序(将最后一行作为第一行,依此类推)

 
 
  1. import scala.io.Source
  2. import java.io.PrintWriter
  3. val source = Source.fromFile("./test.txt")
  4. val reverseLines = source.getLines().toArray.reverse
  5. val pw = new PrintWriter("./output.txt")
  6. reverseLines.foreach(line => pw.write(line +"\n"))
  7. pw.close()

9.2 编写Scala程序,从一个带有制表符的文件读取内容,将每个制表符替换成一组空格,使得制表符隔开的n列仍然保持纵向对齐,并将结果写入同一个文件

 
 
  1. import scala.io.Source
  2. import java.io.PrintWriter
  3. val path = "./test.txt"
  4. val source = Source.fromFile(path).getLines()
  5. val result = for(t <- source) yield t.replaceAll("\\t", " ")
  6. val pw = new PrintWriter("./output.txt")
  7. result.foreach(line => pw.write(line + "\n"))
  8. pw.close()

9.3 编写一小段Scala代码,从一个文件读取内容并把所有字符数大于12的单词打印到控制台。如果你能用单行代码完成会有额外奖励

 
 
  1. import io.Source
  2. Source.fromFile("account.scala").mkString.split("\\s+").foreach(args => if(args.length > 12) println(args))

9.4 编写Scala程序,从包含浮点数的文本文件读取内容,打印出文件中所有浮点数之和,平均值,最大值和最小值

 
 
  1. import scala.io.Source
  2. val nums = Source.fromFile("test.txt").mkString.split("\\s+")
  3. var total = 0d
  4. nums.foreach(total += _.toDouble)
  5. println(total)
  6. println(total/nums.length)
  7. println(nums.max)
  8. println(nums.min)

9.5 编写Scala程序,向文件中写入2的n次方及其倒数,指数n从0到20。对齐各列: 
1 1 
2 0.5 
4 0.25 
... ...

 
 
  1. import java.io.PrintWriter
  2. val pw = new PrintWriter("test.txt")
  3. for(n <- 0 to 200){
  4. val t = BigDecimal(2).pow(n)
  5. pw.write(t.toString())
  6. pw.write("\t\t")
  7. pw.write((1/t).toString())
  8. pw.write("\n")
  9. }
  10. pw.close() //must be closed
  11. [root@master scala]#

9.6 编写正则表达式,匹配Java或C++程序代码中类似

 
 
  1. like this,maybe with \” or\\

这样的带引号的字符串。编写Scala程序将某个源文件中所有类似的字符串打印出来

 
 
  1. import scala.io.Source
  2. val source = Source.fromFile("person.scala").mkString
  3. val pattern = """"([^"\\]*([\\]+"[^"\\]*)*)"""".r
  4. pattern.findAllIn(source).foreach(println)

9.7 编写Scala程序,从文本文件读取内容,并打印出所有的非浮点数的词法单位。要求使用正则表达式

 
 
  1. import io.Source
  2. val source = Source.fromFile("account.scala").mkString
  3. val pattern = """[^((\d+\.){0,1}\d+)^\s+]+""".r
  4. pattern.findAllIn(source).foreach(println)

9.8 编写Scala程序打印出某个网页中所有img标签的src属性。使用正则表达式和分组

 
 
  1. val pattern = """<img[^>]+(src\s*=\s*"[^>^"]+")[^>]*>""".r
  2. val source = scala.io.Source.fromURL("http://www.baidu.com","utf-8").mkString
  3. for(pattern(str) <- pattern.findAllIn(source)) println(str) //正则表达式组

9.9 编写Scala程序,盘点给定目录及其子目录中总共有多少以.class为扩展名的文件

 
 
  1. import java.io.File
  2. val dir = new File(".")
  3. def countClass(dir: File): Int={
  4. var num: Int = 0
  5. val files = dir.listFiles()
  6. num += files.filter(_.isFile).count(_.getName.endsWith(".class"))
  7. files.filter(_.isDirectory).foreach(num += countClass(_))
  8. num
  9. }
  10. println(countClass(dir))

9.10 扩展那个可序列化的Person类,让它能以一个集合保存某个人的朋友信息。构造出一些Person对象,让他们中的一些人成为朋友,然后将Array[Person]保存到文件。将这个数组从文件中重新读出来,校验朋友关系是否完好

 
 
  1. import collection.mutable.ArrayBuffer
  2. import java.io.{ObjectInputStream, FileOutputStream, FileInputStream, ObjectOutputStream}
  3. class Person(var name:String) extends Serializable{
  4. val friends = new ArrayBuffer[Person]()
  5. def addFriend(friend : Person){
  6. friends += friend
  7. }
  8. override def toString() = {
  9. var str = "My name is " + name + " and my friends name is "
  10. friends.foreach(str += _.name + ",")
  11. str
  12. }
  13. }
  14. object Test extends App{
  15. val p1 = new Person("Ivan")
  16. val p2 = new Person("F2")
  17. val p3 = new Person("F3")
  18. p1.addFriend(p2)
  19. p1.addFriend(p3)
  20. println(p1)
  21. val out = new ObjectOutputStream(new FileOutputStream("test.txt"))
  22. out.writeObject(p1)
  23. out.close()
  24. val in = new ObjectInputStream(new FileInputStream("test.txt"))
  25. val p = in.readObject().asInstanceOf[Person]
  26. println(p)
  27. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值