今天將實驗四全部完成。
2. 編寫獨立應用程序實現數據去重
對於兩個輸入文件 A 和 B,編寫 Spark 獨立應用程序,對兩個文件進行合並,並剔除其中重復的內容,得到一個新文件 C。下面是輸入文件和輸出文件的一個樣例,供參考。
輸入文件 A 的樣例如下:
20170101 x
20170102 y
20170103 x
20170104 y
20170105 z
20170106 z
輸入文件 B 的樣例如下:
20170101 y
20170102 y
20170103 x
20170104 z
20170105 y
根據輸入的文件 A 和 B 合並得到的輸出文件 C 的樣例如下:
20170101 x
20170101 y
20170102 y
20170103 x
20170104 y
20170104 z
20170105 y
20170105 z
20170106 z
import scala.io.Source import java.io.PrintWriter import java.io.File import Array._ import scala.util.control._ object exercise4 { def main(args: Array[String]){ File() } def File(){ val AFile=InFile("A.txt") val BFile=InFile("B.txt") var CFile=concat( AFile, BFile) var CFile2=new Array[String](CFile.size) val loop = new Breaks; for(i<-CFile){ loop.breakable{ for(j<- 0 to CFile2.size-1 ){ if(CFile2(j)!=null){if(i==CFile2(j))loop.break;} else {CFile2(j)=i;loop.break;} } } } outFile(CFile2) } def InFile(path:String) : Array[String] ={ val source = Source.fromFile(path, "UTF-8") val lines = source.getLines().toArray return lines } def outFile(data:Array[String]){ val writer = new PrintWriter(new File("C.txt")) for(i <-data) if(i!=null)writer.println(i) writer.close() } }
3. 編寫獨立應用程序實現求平均值問題
每個輸入文件表示班級學生某個學科的成績,每行內容由兩個字段組成,第一個是學生名字,第二個是學生的成績;編寫 Spark 獨立應用程序求出所有學生的平均成績,並輸出到一個新文件中。下面是輸入文件和輸出文件的一個樣例,供參考。
Algorithm 成績:
小明 92
小紅 87
小新 82
小麗 90
Database 成績:
小明 95
小紅 81
小新 89
小麗 85
Python 成績:
小明 82
小紅 83
小新 94
小麗 91
平均成績如下:
(小紅,83.67)
(小新,88.33)
(小明,89.67)
(小麗,88.67)
import scala.io.Source import java.io.PrintWriter import java.io.File import Array._ import scala.util.control._ object exercise4 { def main(args: Array[String]){ File() } def File(){ val data=InFile("student.txt") var student= ofDim[String](4,2) val loop = new Breaks; var time:Int=0 for(i<-data){ var text=String.valueOf(i); var text2=text.split(" ") loop.breakable{ for(j<- 0 to student.size-1){ if(student(j)(0)==null){student(j)(0)=text2(0);student(j)(1)=text2(1);loop.break;} else{ if(text2(0)==student(j)(0)){student(j)(1)=String.valueOf(student(j)(1).toInt+text2(1).toInt);time+=1} } }} } for(j<-0 to 3){ student(j)(1)=String.valueOf(student(j)(1).toDouble/3) } outFile(student) } def InFile(path:String) : Array[String] ={ val source = Source.fromFile(path, "UTF-8") val lines = source.getLines().toArray return lines } def outFile(data:Array[Array[String]]){ val writer = new PrintWriter(new File("avg.txt")) for(i <-0 to data.size-1) writer.println(data(i)(0)+" "+data(i)(1)) writer.close() } }
