在Scala中,如何读取第一行中带有标题的简单CSV文件?

时间:2010-08-31 23:51:57

标签: parsing scala file-io csv

任务是通过一个简单的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()

这种情况下的问题是如何从解析中跳过标题行?

3 个答案:

答案 0 :(得分:29)

您可以使用drop

val iter = src.getLines().drop(1).map(_.split(":"))

来自documentation

  

def drop (n: Int) : Iterator[A]:   推进这个迭代器超过第一个    n 元素,或者长度   迭代器,取较小者。

答案 1 :(得分:12)

这是一个CSV reader in Scala。让人惊讶。

或者,您可以查找CSV reader in Java,并从Scala中调用它。

正确解析CSV文件并非易事。逃避报价,对于初学者来说。

答案 2 :(得分:2)

首先,我使用take(1)读取标题行,然后其余行已经在src迭代器中。这对我来说很好。

val src = Source.fromFile(f).getLines

// assuming first line is a header
val headerLine = src.take(1).next

// processing remaining lines
for(l <- src) {
  // split line by comma and process them
  l.split(",").map { c => 
      // your logic here
  }
}