Best way to read lines in groups in a flat file

╄→гoц情女王★ 提交于 2019-12-11 02:39:31

问题


I have a file which consists of the groups of lines. Each group represents a event. The end of the group is denoted by "END". I can think of using a for loop to loop through the lines, store the intermediate lines and emit the group when "END" is encounter.

But since I would like to do it in Scala. I am wondering if someone can suggest a more functional way to accomplish the same thing?

----------
A
B
C
END
----------
D
E
F
END
----------

回答1:


Just define an iterator to return groups

 def groupIterator(xs:Iterator[String]) =
   new Iterator[List[String]]
    { def hasNext = xs.hasNext; def next = xs.takeWhile(_ != "END").toList}

Testing (with an Iterator[String], but Source.getLines will return you an Iterator for the lines of your file)

val str = """
A 
B
C
END
D
E
F
END
""".trim 

for (g <- groupIterator(str.split('\n').toIterator)) println(g)
                                              //> List(A, B, C)
                                              //| List(D, E, F)


来源:https://stackoverflow.com/questions/32171078/best-way-to-read-lines-in-groups-in-a-flat-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!