首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用FastParse处理文本表?

如何用FastParse处理文本表?
EN

Stack Overflow用户
提问于 2019-05-31 00:34:31
回答 1查看 30关注 0票数 0

我有一个带有单行表的文本文件(制表符分隔),我需要解析它来接收映射(“one”-> 1,"two“-> 2,"three”-> 3)。我不知道该怎么做,甚至根本不确定这是否可能。有什么想法吗,伙计们?

代码语言:javascript
复制
one two three
1   2   3
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-04 17:48:38

好了,我已经知道怎么自己做了。

代码语言:javascript
复制
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))

  }

它将打印出来

代码语言:javascript
复制
Map(one -> 1, two -> 2, three -> 3)
Success value=() successIndex=20
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56382196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档