chapter 9 文件和正则表达式
标签:快学scala
一、笔记
- 读取文件的所有行,可以调用scala.io.Source对象的getLines方法:
import scala.io.Sourceval source = Source.fromFile("test.txt", "UTF-8")val lineIterator = source.getLines//for(i <- lineIterator)println(i)val lines = source.getLines.toArraylines.foreach(println(_))source.close() //记得关闭Source对象
- 读取单个字符,直接把Source当做迭代器,因为Source类扩展自Iterator[Char].
for(c <- source) ...
import scala.io.Sourceval source = Source.fromFile("test.txt", "UTF-8").mkStringval tokens = source.split("\\s+")val numbers = tokens.map(_.toString)numbers.foreach(println(_))
- 写入文本文件:
import java.io.PrintWriterval out = new PrintWriter("test.txt")for(i <- 1 to 100) out.print(i)out.close()
- 访问并遍历文件目录,访问所有的子目录
import java.io.Filedef subdirs(dir: File): Iterator[File] = {val children = dir.listFiles.filter(_.isDirectory)children.toIterator ++ children.toIterator.flatMap(subdirs _)}for(d <- subdirs(dir))
- 进程控制
scala> import sys.process._import sys.process._scala> "ls -al .." ! //!操作符返回的结果时被执行程序的返回值
如果需要在不同的目录下运行进程,或者使用不同的环境变量,使用Process的apply方法来构造ProcessBuilder,给出命令和起始目录,以及一串对偶来设置换进变量。
6. scala.util.matching.Regex类用于正则表达式,构造Regex对象,用String类的r方法。
val numPattern = "[0-9]+".rval wsnumwsPattern = """\s+[0-9]+\s+""".r //包含反斜杠或引号for(matchString <- numPattern,findAllIn("99 bottles, 98 bottles")) 处理matchString //遍历所有匹配项的迭代器scala> numPattern.replaceFirstIn("99 bottles, 98 bottles", "XX")res9: String = XX bottles, 98 bottles
二、习题答案
9.1 编写一小段Scala代码,将某个文件中的行倒转顺序(将最后一行作为第一行,依此类推)
import scala.io.Sourceimport java.io.PrintWriterval source = Source.fromFile("./test.txt")val reverseLines = source.getLines().toArray.reverseval pw = new PrintWriter("./output.txt")reverseLines.foreach(line => pw.write(line +"\n"))pw.close()
9.2 编写Scala程序,从一个带有制表符的文件读取内容,将每个制表符替换成一组空格,使得制表符隔开的n列仍然保持纵向对齐,并将结果写入同一个文件
import scala.io.Sourceimport java.io.PrintWriterval path = "./test.txt"val source = Source.fromFile(path).getLines()val result = for(t <- source) yield t.replaceAll("\\t", " ")val pw = new PrintWriter("./output.txt")result.foreach(line => pw.write(line + "\n"))pw.close()
9.3 编写一小段Scala代码,从一个文件读取内容并把所有字符数大于12的单词打印到控制台。如果你能用单行代码完成会有额外奖励
import io.SourceSource.fromFile("account.scala").mkString.split("\\s+").foreach(args => if(args.length > 12) println(args))
9.4 编写Scala程序,从包含浮点数的文本文件读取内容,打印出文件中所有浮点数之和,平均值,最大值和最小值
import scala.io.Sourceval nums = Source.fromFile("test.txt").mkString.split("\\s+")var total = 0dnums.foreach(total += _.toDouble)println(total)println(total/nums.length)println(nums.max)println(nums.min)
9.5 编写Scala程序,向文件中写入2的n次方及其倒数,指数n从0到20。对齐各列:
1 1
2 0.5
4 0.25
... ...
import java.io.PrintWriterval pw = new PrintWriter("test.txt")for(n <- 0 to 200){val t = BigDecimal(2).pow(n)pw.write(t.toString())pw.write("\t\t")pw.write((1/t).toString())pw.write("\n")}pw.close() //must be closed[root@master scala]#
9.6 编写正则表达式,匹配Java或C++程序代码中类似
”like this,maybe with \” or\\“
这样的带引号的字符串。编写Scala程序将某个源文件中所有类似的字符串打印出来
import scala.io.Sourceval source = Source.fromFile("person.scala").mkStringval pattern = """"([^"\\]*([\\]+"[^"\\]*)*)"""".rpattern.findAllIn(source).foreach(println)
9.7 编写Scala程序,从文本文件读取内容,并打印出所有的非浮点数的词法单位。要求使用正则表达式
import io.Sourceval source = Source.fromFile("account.scala").mkStringval pattern = """[^((\d+\.){0,1}\d+)^\s+]+""".rpattern.findAllIn(source).foreach(println)
9.8 编写Scala程序打印出某个网页中所有img标签的src属性。使用正则表达式和分组
val pattern = """<img[^>]+(src\s*=\s*"[^>^"]+")[^>]*>""".rval source = scala.io.Source.fromURL("http://www.baidu.com","utf-8").mkStringfor(pattern(str) <- pattern.findAllIn(source)) println(str) //正则表达式组
9.9 编写Scala程序,盘点给定目录及其子目录中总共有多少以.class为扩展名的文件
import java.io.Fileval dir = new File(".")def countClass(dir: File): Int={var num: Int = 0val files = dir.listFiles()num += files.filter(_.isFile).count(_.getName.endsWith(".class"))files.filter(_.isDirectory).foreach(num += countClass(_))num}println(countClass(dir))
9.10 扩展那个可序列化的Person类,让它能以一个集合保存某个人的朋友信息。构造出一些Person对象,让他们中的一些人成为朋友,然后将Array[Person]保存到文件。将这个数组从文件中重新读出来,校验朋友关系是否完好
import collection.mutable.ArrayBufferimport java.io.{ObjectInputStream, FileOutputStream, FileInputStream, ObjectOutputStream}class Person(var name:String) extends Serializable{val friends = new ArrayBuffer[Person]()def addFriend(friend : Person){friends += friend}override def toString() = {var str = "My name is " + name + " and my friends name is "friends.foreach(str += _.name + ",")str}}object Test extends App{val p1 = new Person("Ivan")val p2 = new Person("F2")val p3 = new Person("F3")p1.addFriend(p2)p1.addFriend(p3)println(p1)val out = new ObjectOutputStream(new FileOutputStream("test.txt"))out.writeObject(p1)out.close()val in = new ObjectInputStream(new FileInputStream("test.txt"))val p = in.readObject().asInstanceOf[Person]println(p)}
本文介绍Scala中文件的基本操作,包括读取、写入、遍历目录及正则表达式的应用,并通过多个实例演示如何进行文件处理。
979

被折叠的 条评论
为什么被折叠?



