1. 程式人生 > >Scala練習(九)

Scala練習(九)

檔案正則表示式&練習

1. 編寫一小段Scala程式碼,將某個檔案中的行倒轉順序,將最後一行作為第一行,依此類推

程式程式碼:

  1. import scala.io.Source
  2. import java.io.PrintWriter
  3. object ReverseLines extends App {
  4.   val filename="File.txt"
  5.   val RefileName="ReverseFile.txt"
  6.   val source=Source.fromFile("src\\"+filename)
  7.   lazy val ReSource=Source.fromFile("src\\
    "+RefileName)
  8.   lazy val pw = new PrintWriter("src\\"+RefileName)
  9.   val linesIterator=source.getLines()
  10.   val linesRecord=linesIterator.toArray
  11.   val reverseRecord=linesRecord.reverse
  12.   reverseRecord.foreach {
  13.     line =>pw.write(line+"\n")
  14.   }
  15.   pw.close()
  16.   println(filename+"
    檔案內容如下:")
  17.   linesRecord.foreach (line=>println(line))
  18.   println(RefileName+"檔案內容如下:")
  19.   ReSource.getLines().foreach(line=>println(line))
  20. }

執行結果:

File.txt檔案內容如下:

Inc said they plan to form a venture to manage the money market

borrowing and investment activities of both companies.

BP North America is a subsidiary of British Petroleum Co

Plc <BP>, which also owns a 55 pct interest in Standard Oil.

The venture will be called BP/Standard Financial Trading

and will be operated by Standard Oil under the oversight of a

joint management committee.

ReverseFile.txt檔案內容如下:

joint management committee.

and will be operated by Standard Oil under the oversight of a

The venture will be called BP/Standard Financial Trading

Plc <BP>, which also owns a 55 pct interest in Standard Oil.

BP North America is a subsidiary of British Petroleum Co

borrowing and investment activities of both companies.

Inc said they plan to form a venture to manage the money market

2. 編寫Scala程式,從一個帶有製表符的檔案讀取內容,將每個製表符替換成一組空格,使得製表符隔開的n列仍然保持縱向對齊,並將結果寫入同一個檔案

程式程式碼:

  1. object TabSpace extends App{
  2.   val FileName="TabSpace"
  3.   val path="src\\"+FileName+".txt"
  4.   val linesIterator=Source.fromFile(path).getLines()
  5.   lazy val TabIterator=Source.fromFile(path).getLines()
  6.   val linesRecord=linesIterator.toArray
  7.   lazy val pw=new PrintWriter(path)
  8.   println(FileName+"檔案內容如下:")
  9.   linesRecord.foreach(println)
  10.   linesRecord.foreach {
  11.     line =>pw.write(line.replaceAll("\t", "")+"\n")
  12.   }
  13.   pw.close
  14.   println("替換後"+FileName+"檔案內容如下:")
  15.   TabIterator.foreach(println)
  16. }

執行結果:

TabSpace檔案內容如下:

Inc    said    they    plan    to    form    a    venture    to    manage    the    money    market

Inc    ssss    adfs    sdjf    sd    dskl    s    jdakwus    sd    sdskkl    sds    sdsds    djslkl

Inc    said    they    plan    to    form    a    venture    to    manage    the    money    market

Inc    ssss    adfs    sdjf    sd    dskl    s    jdakwus    sd    sdskkl    sds    sdsds    djslkl

Inc    said    they    plan    to    form    a    venture    to    manage    the    money    market        

替換後TabSpace檔案內容如下:

Inc said they plan to form a venture to manage the money market

Inc ssss adfs sdjf sd dskl s jdakwus sd sdskkl sds sdsds djslkl

Inc said they plan to form a venture to manage the money market

Inc ssss adfs sdjf sd dskl s jdakwus sd sdskkl sds sdsds djslkl

Inc said they plan to form a venture to manage the money market

3. 編寫一小段Scala程式碼,從一個檔案讀取內容並把所有字元數大於12的單詞列印到控制檯。如果你能用單行程式碼完成會有額外獎勵

程式程式碼:

  1. object CheckString extends App{
  2.   val FileName="CheckString"
  3.   val path="src\\"+FileName+".txt"
  4.   println(FileName+"檔案中長度大於12的字串為:")
  5.   io.Source.fromFile(path).mkString.split("\\s+").foreach (str => if(str.length()>12) println(str))
  6. }

執行結果:

CheckString檔案中長度大於12的字串為:

Incsaidtheyplan

jdakwussdsdskkl

managethemoneymarket

dsklsjdakwussdsdskkl

venturetomanagethe

4. 編寫Scala程式,從包含浮點數的文字檔案讀取內容,打印出檔案中所有浮點數之和,平均值,最大值和最小值

程式程式碼:

  1. object ReadNumber extends App{
  2.   val pattern="(\\d+[.]\\d+)".r
  3.   val pattern1="^\\d+(\\.\\d+)?".r
  4.   val pattern2="[0-9]+(\\.\\d+)?".r
  5.   val FileName="NumberFile"
  6.   val path = "src\\"+FileName+".txt"
  7.   val FileStr=io.Source.fromFile(path).mkString
  8.   val StrArray=pattern2.findAllIn(FileStr).toArray
  9.   var total=0d
  10.   val len=StrArray.length
  11.   StrArray.foreach (total +=_.toDouble)
  12.   println("文字中浮點數總和: "+total)
  13.   println("文字中浮點數平均數: "+total/len+len)
  14.   println("文字中浮點數的最大值: "+StrArray.max)
  15.   println("文字中浮點數的最大值: "+StrArray.min)
  16. }

測試資料:

joint    55    666.0    management    13.5    committee    12.5

joint    6.0    123.4    management    3.14    committee    170.5

joint    52    63.32    management    10.4    committee    12.5

執行結果:

文字中浮點數總和: 1188.26

文字中浮點數平均數: 99.0216666666666612

文字中浮點數的最大值: 666.0

文字中浮點數的最大值: 10.4

5. 編寫Scala程式,向檔案中寫入2的n次方及其倒數,指數n從0到20。對齊各列:

1 1

2 0.5

4 0.25

... ...

程式程式碼:

  1. import java.io.PrintWriter
  2. object index extends App{
  3.   val FileName="Index"
  4.   val path="src\\"+FileName+".txt"
  5.   val out=new PrintWriter(path)
  6.   for (i <- 0 to 20)
  7.     out.println(OutIndex(i))
  8.   out.close
  9.   def OutIndex(n:Int)={
  10.     val value=math.pow(2, n)
  11.     ""*4+value.toInt+""*(11-value.toString().size)+math.pow(2, -n)
  12.   }
  13. }

執行結果:

1 1.0

2 0.5

4 0.25

8 0.125

16 0.0625

32 0.03125

64 0.015625

128 0.0078125

256 0.00390625

512 0.001953125

1024 9.765625E-4

2048 4.8828125E-4

4096 2.44140625E-4

8192 1.220703125E-4

16384 6.103515625E-5

32768 3.0517578125E-5

65536 1.52587890625E-5

131072 7.62939453125E-6

262144 3.814697265625E-6

524288 1.9073486328125E-6

1048576 9.5367431640625E-7

6. 編寫正則表示式,匹配Java或C++程式程式碼中類似"like this,maybe with \" or\\"這樣的帶引號的字串。編寫Scala程式將某個原始檔中所有類似的字串打印出來

描述:沒看太懂,按自己意思來的

程式程式碼:

  1. import scala.io.Source
  2. object regExp extends App{
  3.   val FileName="Regexp"
  4.   val path="src\\"+FileName+".txt"
  5.   val pat1=""""like thismaybe with \\" or\\{2}"""".r
  6.   val pat2="""like thismaybe with \\" or\\{2}""".r
  7.   val pat3="""\w+\s+\\"""".r
  8.   val linesIterator1=Source.fromFile(path).getLines()
  9.   val linesIterator2=Source.fromFile(path).getLines()
  10.   val linesIterator3=Source.fromFile(path).getLines()
  11.   println("文字中包含:"+""""like thismaybe with \" or\\"""")
  12.   linesIterator1.foreach(line=>pat1.findAllIn(line).foreach (println))
  13.   println("文字中包含:"+"""like thismaybe with \" or\\""")
  14.   linesIterator2.foreach(line=>pat2.findAllIn(line).foreach (println))
  15.   println("文字中包含:"+"\\w+\\s+\"")
  16.   linesIterator3.foreach(line=>pat3.findAllIn(line).foreach(println))
  17. }

執行結果:

文字中包含:"like thismaybe with \" or\\"

"like thismaybe with \" or\\"

文字中包含:like thismaybe with \" or\\

like thismaybe with \" or\\

like thismaybe with \" or\\

like thismaybe with \" or\\

文字中包含:\w+\s+"

with \"

with \"

with \"

7. 編寫Scala程式,從文字檔案讀取內容,並打印出所有的非浮點數的詞法單位。要求使用正則表示式

程式程式碼:

  1. import io.Source
  2. object NonFloat extends App{
  3.   val source = Source.fromFile("src\\NumberFile.txt").mkString
  4.   val pat1 = """[^((\d+\.){0,1}\d+)^\s+]+$""".r//去掉+試試
  5.   val pat2 = """^((?!^[-]?\d*\.\d+$).)+$""".r
  6.   println("模式1不包含整數:")
  7.   for(token <- source.split("\\s+")){
  8.     for(word <- pat1.findAllIn(token))
  9.       if(!word.equals("")){
  10.         println(token)
  11.       }
  12.   }
  13.   println("模式2包含整數:")
  14.   for(token <- source.split("\\s+")){
  15.     for(word <- pat2.findAllIn(token))
  16.       println(word)
  17.   }
  18. }

測試資料:

joint    55    666.0    management    13.5    committee    12.5

joint    6.0    123.4    management    3.14    committee    170.5

joint    52    63.32    management    10.4    committee    12.5

0.12t    20    5.6ef    45.77ghjss    5.94    dfdxsccxz    7.9

執行結果:

模式1不包含整數:

joint

management

committee

joint

management

committee

joint

management

committee

0.12t

5.6ef

45.77ghjss

dfdxsccxz

模式2包含整數:

joint

55

management

committee

joint

management

committee

joint

52

management

committee

0.12t

20

5.6ef

45.77ghjss

dfdxsccxz

8. 編寫Scala程式打印出某個網頁中所有img標籤的src屬性。使用正則表示式和分組

程式程式碼:

  1. object WebSrc extends App{
  2.   val pat = """<img.*?src=["'](.+?)["'].*?>""".r
  3.   for (pat(src) <-pat.findAllIn(io.Source.fromURL("http://www.baidu.com").mkString)) {
  4.     println(src)
  5.   }
  6. }

執行結果:

//www.baidu.com/img/bd_logo1.png

//www.baidu.com/img/baidu_jgylogo3.gif

9. 編寫Scala程式,盤點給定目錄及其子目錄中總共有多少以.class為副檔名的檔案

程式程式碼:

  1. import java.io.File
  2. object NumDir extends App{
  3.   val path = "."
  4.   val dir = new File(path)
  5.   def subdirs(dir:File):Iterator[File]={
  6.     val children = dir.listFiles().filter(_.getName.endsWith("class"))
  7.     children.toIterator ++ dir.listFiles().filter(_.isDirectory).toIterator.flatMap(subdirs _)
  8.   }
  9.   val n = subdirs(dir).length
  10.   println(n)
  11. }

執行結果:

52

10. 擴充套件那個可序列化的Person類,讓它能以一個集合儲存某個人的朋友資訊。構造出一些Person物件,讓他們中的一些人成為朋友,然後將Array[Person]儲存到檔案。將這個陣列從檔案中重新讀出來,校驗朋友關係是否完好 注意,請在main中執行。指令碼執行無法序列化。

程式程式碼:

  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 PersonTest extends App{
  15.   val p1 = new Person("JackChen")
  16.   val p2 = new Person("Jhon·D")
  17.   val p3 = new Person("Sunday")
  18.   p1.addFriend(p2)
  19.   p1.addFriend(p3)
  20.   println(p1)
  21.   val out = new ObjectOutputStream(new FileOutputStream("src\\Person.txt"))
  22.   out.writeObject(p1)
  23.   out.close()
  24.   val in = new ObjectInputStream(new FileInputStream("src\\Person.txt"))
  25.   val p = in.readObject().asInstanceOf[Person]
  26.   println(p)
  27. }

執行結果:

My name is JackChen and my friends name is Jhon·D,Sunday

My name is JackChen and my friends name is Jhon·D,Sunday

本文轉自http://www.cnblogs.com/sunddenly/p/4444626.html