我有一个带有单行表(制表符分隔)的文本文件,我需要对其进行解析以接收Map(“一个”-> 1,“两个”-> 2,“三个”-> 3)。我不知道该怎么做,甚至不能确定它是否可行。有想法吗?
// MEmories
// -Lg7rOvv_pO3rXiUnRc_
// body: "It was fun"
// date: 1559481142000
// imageRef: "my_memory.png"
// title: "my memory"
// Users
// zW0CYeNzzvXZw6TbC42Tud41bzN2
// email: "memory@gmail.com"
// name: "memory"
// memories: -Lr2f7-11e9-bc42-526af7764f64
// User-MEmories
// -Lr2f7-11e9-bc42-526af7764f64
// -Lg7rOvv_pO3rXiUnRc_
答案 0 :(得分:0)
好吧,我已经想出了自己的方法。
val lines = Source.fromResource("test.txt").getLines().mkString("\r\n")
def sentence[_: P] = P(CharIn("0-9", "a-z").rep(1).!)
def tableHeader[_: P] = P((sentence.! ~ "\t".?).rep ~ lineSeparator)
def tableRow[_: P](h: Seq[String]) = P((sentence.! ~ "\t".?).rep ~ (lineSeparator | End))
.map(r => println(h.zip(r).toMap))
def singleRowTable[_: P] = P(tableHeader.flatMap(tableRow))
def lineSeparator[_: P] = P("\r\n" | "\r" | "\n")
def parseA[_: P] = P(singleRowTable)
parse(lines, parseA(_), true) match {
case Parsed.Success(value, successIndex) =>
println("Success value=" + value +" successIndex=" + successIndex)
case f @ Parsed.Failure(label, index, extra) =>
println("Failure " + f.trace(true))
}
它将打印
Map(one -> 1, two -> 2, three -> 3)
Success value=() successIndex=20