1. 編寫一小段Scala代碼,將某個文件中的行倒轉順序,將最後一行做爲第一行,依此類推 正則表達式
程序代碼:數組
-
import scala.io.Source
-
import java.io.PrintWriter
-
-
object ReverseLines extends App {
-
val filename="File.txt"
-
val RefileName="ReverseFile.txt"
-
-
val source=Source.fromFile("src\\"+filename)
-
lazy val ReSource=Source.fromFile("src\\"+RefileName)
-
lazy val pw = new PrintWriter("src\\"+RefileName)
-
-
val linesIterator=source.getLines()
-
val linesRecord=linesIterator.toArray
-
val reverseRecord=linesRecord.reverse
-
-
reverseRecord.foreach {
-
line =>pw.write(line+"\n")
-
}
-
pw.close()
-
-
println(filename+"
文件內容以下:
")
-
linesRecord.foreach (line=>println(line))
-
-
println(RefileName+"
文件內容以下:
")
-
ReSource.getLines().foreach(line=>println(line))
-
}
運行結果:ide
File.txt文件內容以下: 測試
Inc said they plan to form a venture to manage the money market this
borrowing and investment activities of both companies. spa
BP North America is a subsidiary of British Petroleum Co scala
Plc <BP>, which also owns a 55 pct interest in Standard Oil. rest
The venture will be called BP/Standard Financial Trading orm
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列仍然保持縱向對齊,並將結果寫入同一個文件
程序代碼:
-
object TabSpace extends App{
-
val FileName="TabSpace"
-
val path="src\\"+FileName+".txt"
-
val linesIterator=Source.fromFile(path).getLines()
-
lazy val TabIterator=Source.fromFile(path).getLines()
-
val linesRecord=linesIterator.toArray
-
lazy val pw=new PrintWriter(path)
-
println(FileName+"
文件內容以下:
")
-
linesRecord.foreach(println)
-
linesRecord.foreach {
-
line =>pw.write(line.replaceAll("\t", "")+"\n")
-
}
-
pw.close
-
println("
替換後
"+FileName+"
文件內容以下:
")
-
TabIterator.foreach(println)
-
-
}
運行結果:
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的單詞打印到控制檯。若是你能用單行代碼完成會有額外獎勵
程序代碼:
-
object CheckString extends App{
-
val FileName="CheckString"
-
val path="src\\"+FileName+".txt"
-
println(FileName+"
文件中長度大於12的字符串爲:
")
-
io.Source.fromFile(path).mkString.split("\\s+").foreach (str => if(str.length()>12) println(str))
-
}
運行結果:
CheckString文件中長度大於12的字符串爲:
Incsaidtheyplan
jdakwussdsdskkl
managethemoneymarket
dsklsjdakwussdsdskkl
venturetomanagethe
4. 編寫Scala程序,從包含浮點數的文本文件讀取內容,打印出文件中全部浮點數之和,平均值,最大值和最小值
程序代碼:
-
object ReadNumber
extends App{
-
val pattern="
(\\d+[.]\\d+)".r
-
val pattern1="
^\\d+(\\.\\d+)?".r
-
val pattern2="
[0-9]+(\\.\\d+)?".r
-
val FileName="
NumberFile"
-
val path = "
src\\"+FileName+"
.txt"
-
val FileStr=io.Source.fromFile(path).mkString
-
val StrArray=pattern2.findAllIn(FileStr).toArray
-
var total=0d
-
val len=StrArray.length
-
StrArray.foreach (total +=_.toDouble)
-
println("
文本中浮點數總和: "+total)
-
println("
文本中浮點數平均數: "+total/len+len)
-
println("
文本中浮點數的最大值: "+StrArray.max)
-
println("
文本中浮點數的最大值: "+StrArray.min)
-
}
測試數據:
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
... ...
程序代碼:
-
import java.io.PrintWriter
-
-
object index extends App{
-
val FileName="Index"
-
val path="src\\"+FileName+".txt"
-
val out=new PrintWriter(path)
-
for (i <- 0 to 20)
-
out.println(OutIndex(i))
-
out.close
-
def OutIndex(n:Int)={
-
val value=math.pow(2, n)
-
""*4+value.toInt+""*(11-value.toString().size)+math.pow(2, -n)
-
}
-
}
運行結果:
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程序將某個源文件中全部相似的字符串打印出來
描述:沒看太懂,按本身意思來的
程序代碼:
-
import
scala.io.Source
-
-
object regExp extends App{
-
val FileName="Regexp"
-
val path="src\\"+FileName+".txt"
-
val pat1=""""like this
,
maybe with \\" or\\{2}"""".r
-
val pat2="""like this
,
maybe with \\" or\\{2}""".r
-
val pat3="""\w+\s+\\"""".r
-
val linesIterator1=Source.fromFile(path).getLines()
-
val linesIterator2=Source.fromFile(path).getLines()
-
val linesIterator3=Source.fromFile(path).getLines()
-
println("
文本中包含:
"+""""like this
,
maybe with \" or\\"""")
-
linesIterator1.foreach(line=>pat1.findAllIn(line).foreach (println))
-
println("
文本中包含:
"+"""like this
,
maybe with \" or\\""")
-
linesIterator2.foreach(line=>pat2.findAllIn(line).foreach (println))
-
println("
文本中包含:
"+"\\w+\\s+\"")
-
linesIterator3.foreach(line=>pat3.findAllIn(line).foreach(println))
-
}
運行結果:
文本中包含:"like this,maybe with \" or\\"
"like this,maybe with \" or\\"
文本中包含:like this,maybe with \" or\\
like this,maybe with \" or\\
like this,maybe with \" or\\
like this,maybe with \" or\\
文本中包含:\w+\s+"
with \"
with \"
with \"
7. 編寫Scala程序,從文本文件讀取內容,並打印出全部的非浮點數的詞法單位。要求使用正則表達式
程序代碼:
-
import io.Source
-
object NonFloat extends App{
-
val source = Source.fromFile("src\\NumberFile.txt").mkString
-
val pat1 = """[^((\d+\.){0,1}\d+)^\s+]+$""".r//
去掉
+試試
-
val pat2 = """^((?!^[-]?\d*\.\d+$).)+$""".r
-
println("
模式1不包含整數:
")
-
for(token <- source.split("\\s+")){
-
for(word <- pat1.findAllIn(token))
-
if(!word.equals("")){
-
println(token)
-
}
-
}
-
println("
模式2包含整數:
")
-
for(token <- source.split("\\s+")){
-
for(word <- pat2.findAllIn(token))
-
println(word)
-
}
-
}
測試數據:
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屬性。使用正則表達式和分組
程序代碼:
-
object WebSrc
extends App{
-
val pat = """<img.*?src=["
'](.+?)["'].*?>""".r
-
for (pat(src) <-pat.findAllIn(io.Source.fromURL("
http://www.baidu.com").mkString)) {
-
println(src)
-
}
-
}
運行結果:
//www.baidu.com/img/bd_logo1.png
//www.baidu.com/img/baidu_jgylogo3.gif
9. 編寫Scala程序,盤點給定目錄及其子目錄中總共有多少以.class爲擴展名的文件
程序代碼:
-
import java.io.File
-
object NumDir
extends App{
-
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)
-
}
運行結果:
52
10. 擴展那個可序列化的Person類,讓它能以一個集合保存某我的的朋友信息。構造出一些Person對象,讓他們中的一些人成爲朋友,而後將Array[Person]保存到文件。將這個數組從文件中從新讀出來,校驗朋友關係是否無缺 注意,請在main中執行。腳本執行沒法序列化。
程序代碼:
-
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 PersonTest extends App{
-
val p1 = new Person("JackChen")
-
val p2 = new Person("Jhon·D")
-
val p3 = new Person("Sunday")
-
p1.addFriend(p2)
-
p1.addFriend(p3)
-
println(p1)
-
val out = new ObjectOutputStream(new FileOutputStream("src\\Person.txt"))
-
out.writeObject(p1)
-
out.close()
-
val in = new ObjectInputStream(new FileInputStream("src\\Person.txt"))
-
val p = in.readObject().asInstanceOf[Person]
-
println(p)
-
}
運行結果:
My name is JackChen and my friends name is Jhon·D,Sunday,
My name is JackChen and my friends name is Jhon·D,Sunday,
若是,您認爲閱讀這篇博客讓您有些收穫,不妨點擊一下右下角的【推薦】。
若是,您但願更容易地發現個人新博客,不妨點擊一下左下角的【關注我】。
若是,您對個人博客所講述的內容有興趣,請繼續關注個人後續博客,我是【Sunddenly】。
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利