本文介绍了在平面文件中按组读取行的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由行组组成的文件.每个组代表一个事件.组的结尾由END"表示.我可以考虑使用 for 循环遍历行,存储中间行并在遇到END"时发出组.

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.

但是因为我想在 Scala 中进行.我想知道是否有人可以建议一种更实用的方法来完成同样的事情?

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
----------

推荐答案

只需定义一个迭代器即可返回组

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}

测试(使用 Iterator[String],但 Source.getLines 会返回一个文件行的迭代器)

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)

这篇关于在平面文件中按组读取行的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:47