该任务是通过一个简单的CSV文件中的关键字段值(用逗号作为分隔符,没有用字段引起双引号,从不包含字段中的逗号)来查找特定字段(按行中的数字)的值。在第一行。
用户uynhjl给出了一个示例(但以不同的字符作为分隔符):
val src = Source.fromFile("/etc/passwd")
val iter = src.getLines().map(_.split(":"))
// print the uid for Guest
iter.find(_(0) == "Guest") foreach (a => println(a(2)))
// the rest of iter is not processed
src.close()
在这种情况下的问题是如何跳过 header 行来进行解析?
最佳答案
您可以只使用drop
:
val iter = src.getLines().drop(1).map(_.split(":"))
从documentation:
def drop (n: Int) : Iterator[A]
: Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.
关于parsing - 在Scala中,如何读取在第一行中具有标题的简单CSV文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614041/