快學Scala習題解答—第九章 文件和正則表達式

[size=large][b]10 文件和正則表達式[/b][/size]

[b]10.1 編寫一小段Scala代碼,將某個文件中的行倒轉順序(將最後一行作爲第一行,依此類推)[/b]
import io.Source
import java.io.PrintWriter

val path = "test.txt"

val reader = Source.fromFile(path).getLines()

val result = reader.toArray.reverse

val pw = new PrintWriter(path)

result.foreach(line => pw.write(line + "\n"))

pw.close()


[b]10.2 編寫Scala程序,從一個帶有製表符的文件讀取內容,將每個製表符替換成一組空格,使得製表符隔開的n列仍然保持縱向對齊,並將結果寫入同一個文件[/b]
import io.Source
import java.io.PrintWriter

val path = "test.txt"

val reader = Source.fromFile(path).getLines()

val result = for ( t <- reader) yield t.replaceAll("\\t"," ")

val pw = new PrintWriter(path)

result.foreach(line => pw.write(line + "\n"))

pw.close()


[b]10.3 編寫一小段Scala代碼,從一個文件讀取內容並把所有字符數大於12的單詞打印到控制檯。如果你能用單行代碼完成會有額外獎勵[/b]
import io.Source

Source.fromFile("test.txt").mkString.split("\\s+").foreach(arg => if(arg.length > 12) println(arg))


[b]10.4 編寫Scala程序,從包含浮點數的文本文件讀取內容,打印出文件中所有浮點數之和,平均值,最大值和最小值[/b]
import io.Source

val nums = Source.fromFile("test.txt").mkString.split("\\s+")

var total = 0d

nums.foreach(total += _.toDouble)

println(total)
println(total/nums.length)
println(nums.max)
println(nums.min)

[b]
10.5 編寫Scala程序,向文件中寫入2的n次方及其倒數,指數n從0到20。對齊各列:
1 1
2 0.5
4 0.25
... ...[/b]
import java.io.PrintWriter

val pw = new PrintWriter("test.txt")

for ( n <- 0 to 20){
val t = BigDecimal(2).pow(n)
pw.write(t.toString())
pw.write("\t\t")
pw.write((1/t).toString())
pw.write("\n")
}

pw.close()


[b]10.6 編寫正則表達式,匹配Java或C++程序代碼中類似"like this,maybe with \" or\\"這樣的帶引號的字符串。編寫Scala程序將某個源文件中所有類似的字符串打印出來[/b]
import io.Source

val source = Source.fromFile("test.txt").mkString

val pattern = "\\w+\\s+\"".r

pattern.findAllIn(source).foreach(println)


[b]10.7 編寫Scala程序,從文本文件讀取內容,並打印出所有的非浮點數的詞法單位。要求使用正則表達式[/b]
import io.Source

val source = Source.fromFile("test.txt").mkString

val pattern = """[^((\d+\.){0,1}\d+)^\s+]+""".r

pattern.findAllIn(source).foreach(println)


[b]10.8 編寫Scala程序打印出某個網頁中所有img標籤的src屬性。使用正則表達式和分組[/b]
import io.Source

val source = Source.fromFile("D:\\ProgramCodes\\ScalaTest\\src\\test.txt").mkString
val pattern = """<img[^>]+(src\s*=\s*"[^>^"]+")[^>]*>""".r

for (pattern(str) <- pattern.findAllIn(source)) println(str)


[b]10.9 編寫Scala程序,盤點給定目錄及其子目錄中總共有多少以.class爲擴展名的文件[/b]
import java.io.File

val path = "."

val dir = new File(path)


def subdirs(dir:File):Iterator[File]={
val children = dir.listFiles().filter(_.getName.endsWith("class"))
children.toIterator ++ dir.listFiles().filter(_.isDirectory).toIterator.flatMap(subdirs _)
}

val n = subdirs(dir).length

println(n)


[b]10.10 擴展那個可序列化的Person類,讓它能以一個集合保存某個人的朋友信息。構造出一些Person對象,讓他們中的一些人成爲朋友,然後將Array[Person]保存到文件。將這個數組從文件中重新讀出來,校驗朋友關係是否完好
注意,請在main中執行。腳本執行無法序列化。[/b]
import collection.mutable.ArrayBuffer
import 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)
}


[b]Blog URL:[/b][url]http://www.ivanpig.com/blog/?p=478[/url]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章