是否有一种方法来设置它,以便您可以创建一个循环/条件语句,允许您获得您要寻找的单词,并且只在那里循环?
例如,csv文件:姓名、年份、语言凯尔,1998年;英语凯尔,2011年;英语凯尔,1879年;法国乔治,1978年;西班牙语佐伊,2000年,英语
所以在寻找凯尔的时候,它只会得到凯尔的价值而不是其他的名字?
预期收益:凯尔,1998年;英格兰凯尔,2011年;英格兰凯尔,1879年;法语
抱歉,如果这很简单,但我对Scala还不太熟悉,也不太确定。
发布于 2022-03-05 22:45:52
步骤1:读取文件
import scala.io.Source
import scala.util.Using
Using(Source.fromFile(filename)) { source =>
val lines =
source.getLines()
}步骤2:处理每一行。
我们将将它们解析为case类实例,并删除所有损坏的字段:
final case class Record(name: String, year: Int, language: String)
object Record {
def parseLine(line: String): Option[Record] =
line.split(',').toList match {
case nameRaw :: yearRaw :: languageRaw :: Nil =>
yearRaw.trim.toIntOption.map { year =>
Record(
name = nameRaw.trim,
year = year,
language = languageRaw.trim.toLowerCase
)
}
case _ =>
None
}
}
val records =
lines.flatMap(Record.parsLine)步骤3:按所需谓词筛选记录:
val namedKyle: Record => Boolean =
record => record.name.toLowerCase == "kyle"
val validRecords =
records.filter(namedKyle)步骤4:在严格的集合中实现结果,如List
val result =
validRecords.toList步骤5:将所有内容组合在一起:
def readValidRecords(filename: String)(predicate: Record => Boolean): Try[List[Record]] =
Using(Source.fromFile(filename)) { source =>
source
.getLines()
.flatMap(Record.parsLine)
.filter(predicate)
.toList
}https://stackoverflow.com/questions/71365858
复制相似问题