在Scala中,如何读取一个简单的CSV文件,其中有一个标题在它的第一行? [英] In Scala, how to read a simple CSV file having a header in it's first line?

查看:5165
本文介绍了在Scala中,如何读取一个简单的CSV文件,其中有一个标题在它的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



< http://www.scala-lang.org/api/current/scala/collection/Iterator.html =noreferrer>文档:

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆