簡體   English   中英

遍歷scala中的日期范圍

[英]Iterate through range of dates in scala

如何確保下面的o_data追加多個文件? 假設每個日期(從2018-09-01開始)有一個文件(制表符分隔值),我想附加所有30個文件(9/1〜9/30)並將其存儲在o_data變量中。 我最初的猜測是使用for循環,但對scala不熟悉,不確定從哪里開始。

以下適用於一個文件。

val o_data = "test::repo/shared/[2018-09-01]"

然后我用

val data = tes.read(o_data)

讀取文件,但是為了讓我獲得一個月的數據,我唯一能做的就是為每個文件創建不同的val,因此o_data2,o_data3 ... o_data30並運行read函數每個文件並在末尾將其合並,但這聽起來很愚蠢...

您可以執行以下操作:

    val o_data = (1 to 30).map(d => {
      val df = if(d<10) "0"+d else d 
      s"test::repo/shared/[2018-09-$df]"
    })

完成上述操作后, o_data將為:

test::repo/shared/[2018-09-01]
test::repo/shared/[2018-09-02]
test::repo/shared/[2018-09-03]
test::repo/shared/[2018-09-04]
test::repo/shared/[2018-09-05]
...
test::repo/shared/[2018-09-28]
test::repo/shared/[2018-09-29]
test::repo/shared/[2018-09-30]

這個想法是使用Scala的字符串插值從數字構造正確的文件名。 if語句確保小於10的數字前有一個0

編輯:如果您喜歡一個班輪(就像我一樣),則可以將上面的內容重寫為(再次使用能力字符串串的報價,並感謝@Dima的建議):

val o_data=val files = (1 to 30)map(d =>f"test::repo/shared/[2018-09-$d%02d]")

編輯2:由於這些是文件名,因此我們可以使用文件API來讀取它們:

val allLines:mutable.Buffer[String] = mutable.Buffer()
o_data.foreach(filename => {
  val lines = tes.read(filename)
  allLines.append(line)
  ... //do stuff with lines read from file: "filename"
}
allLines foreach println

當然,您應該注意讀取一堆文件(文件不存在等)可能引起的任何錯誤。 foreach循環讀取o_data中存在的文件名,並將對其進行逐一處理。 您可以在此處看到一些有關如何打開和讀取文件的示例。

編輯3:聚合文件中的所有行也可以使用更實用的樣式來實現:

import scala.io.Source.fromFile
val allLines = files.foldLeft(Iterator[String]())((f, g) => f ++ fromFile(g).getLines)
allLines foreach println

此方法的優點在於,它串聯了多個迭代器,如果文件很大,這些迭代器可能會有所幫助。 如果需要獲取字符串,可以執行以下操作:

import scala.io.Source.fromFile
val allLines = files.foldLeft(List[String]())((f, g) => f ++ fromFile(g).getLines.toList)
allLines foreach println

該方法可以通過任何引起文件中行對齊的文件讀取技術(OP的問題中的data.read )來成功實現。

要獲取任何月份的范圍,請使用java.time庫。 看一下這個

scala> val o_data =  (1 to 31)
o_data: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31)

scala> val (year,month) = (2018,9)
year: Int = 2018
month: Int = 9

scala> o_data.map( x => { val y=java.time.LocalDate.of(year,month,1); y.plusDays(x-1)} ).filter( _.getMonthValue==month).map(s"test::repo/shared/["+_.toString+"]").foreach(println)
test::repo/shared/[2018-09-01]
test::repo/shared/[2018-09-02]
test::repo/shared/[2018-09-03]
test::repo/shared/[2018-09-04]
test::repo/shared/[2018-09-05]
test::repo/shared/[2018-09-06]
.........
test::repo/shared/[2018-09-30]

scala>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM