Scala:将表格绘制到控制台

标签 scala console-application rendering tabular

我需要在控制台中显示一个表格。

我的简单解决方案(如果您称其为“解决方案”)如下:

  override def toString() = {
    var res = "\n"
      var counter = 1;
      res += stateDb._1 + "\n"
      res += "  +----------------------------+\n"
      res += "  +     State Table            +\n"
      res += "  +----------------------------+\n"
      for (entry <- stateDb._2) {
        res += "  | " + counter + "\t | " + entry._1 + " | " + entry._2 + " |\n"
        counter += 1;
      }
      res += "  +----------------------------+\n"
      res += "\n"
    res

  }

我们不必争论这一点

  • a 显示时看起来很糟糕
  • b 代码看起来有点困惑

实际上,这样的问题是针对 C# 提出的,但我也想知道 Scala 的一个很好的解决方案。

那么在 Scala 中将这样的表格绘制到控制台的(好/好/简单/其他)方法是什么?

-------------------------------------------------------------------------
|    Column 1     |    Column 2     |    Column 3     |    Column 4     |
-------------------------------------------------------------------------
|                 |                 |                 |                 |
|                 |                 |                 |                 |
|                 |                 |                 |                 |
-------------------------------------------------------------------------

最佳答案

我从当前项目中提取了以下内容:

object Tabulator {
  def format(table: Seq[Seq[Any]]) = table match {
    case Seq() => ""
    case _ => 
      val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length)
      val colSizes = for (col <- sizes.transpose) yield col.max
      val rows = for (row <- table) yield formatRow(row, colSizes)
      formatRows(rowSeparator(colSizes), rows)
  }

  def formatRows(rowSeparator: String, rows: Seq[String]): String = (
    rowSeparator :: 
    rows.head :: 
    rowSeparator :: 
    rows.tail.toList ::: 
    rowSeparator :: 
    List()).mkString("\n")

  def formatRow(row: Seq[Any], colSizes: Seq[Int]) = {
    val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item))
    cells.mkString("|", "|", "|")
  }

  def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+")
}

scala> Tabulator.format(List(List("head1", "head2", "head3"), List("one", "two", "three"), List("four", "five", "six")))
res1: java.lang.String = 
+-----+-----+-----+
|head1|head2|head3|
+-----+-----+-----+
|  one|  two|three|
| four| five|  six|
+-----+-----+-----+

关于Scala:将表格绘制到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7539831/

相关文章:

scala - 如何使用带管道的多字符分隔符进行拆分?

scala - 缺少参数类型

c# - 让任务在控制台应用程序的后台永久运行

c# - 尝试从预览运行屏幕保护程序时出现 SHIM_NOVERSION_FOUND 错误

c# - 空分号和开闭花括号有效

javascript - 用 HTML 渲染 4000 张图像?

scala - .sc 和 .scala 文件有什么区别?

使用 sbt 程序集构建 Scala 代码,失败

opengl - AMD Mantle API 文档

css - IE 忽略填充时空白 : nowrap