Как обрабатывать текстовые таблицы с FastParse? - PullRequest
0 голосов
/ 30 мая 2019

У меня есть текстовый файл с одной строкой таблицы (табуляция разделена), и мне нужно проанализировать его, чтобы получить карту («один» -> 1, «два» -> 2, «три» -> 3). Я не могу понять, как это сделать, и даже не уверен, что это вообще возможно. Есть идеи, ребята?

one two three
1   2   3

1 Ответ

0 голосов
/ 04 июня 2019

Хорошо, я понял, как это сделать сам.

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
...