在Scala中,如何读取第一行带有标题的简单CSV文件? [英] In Scala, how to read a simple CSV file having a header in its first line?
问题描述
任务是通过简单的CSV文件中的关键字段值(通过逗号作为分隔符,不包含字段引号,从不在字段内使用逗号)来查找特定字段(按行中的数字)的值,在第一行中有一个标题.
The task is to look for a specific field (by it's number in line) value by a key field value in a simple CSV file (just commas as separators, no field-enclosing quotes, never a comma inside a field), having a header in its first line.
用户uynhjl给出了一个示例(但用不同的字符作为分隔符):
User uynhjl has given an example (but with a different character as a separator):
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()
在这种情况下,问题是如何跳过标头行进行解析?
the question in this case is how to skip a header line from parsing?
推荐答案
您可以只使用drop
:
val iter = src.getLines().drop(1).map(_.split(":"))
从文档:
def drop (n: Int) : Iterator[A]
: 将此迭代器推进到第一个迭代器之前 n 元素,或 迭代器,以较小者为准.
def drop (n: Int) : Iterator[A]
: Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.
这篇关于在Scala中,如何读取第一行带有标题的简单CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!