如何使用 FastParse 处理文本表格?
How to handle text tables with FastParse?
我有单行 table 的文本文件(制表符分隔),我需要解析它以接收 Map("one" -> 1, "two" -> 2, "three" -> 3).我不知道该怎么做,甚至根本不确定它是否可能。大家有什么想法吗?
one two three
1 2 3
好的,我已经自己想出办法了。
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
我有单行 table 的文本文件(制表符分隔),我需要解析它以接收 Map("one" -> 1, "two" -> 2, "three" -> 3).我不知道该怎么做,甚至根本不确定它是否可能。大家有什么想法吗?
one two three
1 2 3
好的,我已经自己想出办法了。
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