在Go语言中打印表格的高效方法是什么?

huangapple go评论101阅读模式
英文:

The efficient way to print a table in GO

问题

我想知道在Go语言中打印表格的简单高效的方法。我找到的解决方案虽然可行,但非常丑陋。

非常感谢!

outfile := "file.tsv"
f, err := os.Create(outfile)
var buffer bytes.Buffer

buffer.WriteString(a[i])
buffer.WriteString("\t")
buffer.WriteString(a[j])
buffer.WriteString("\t")
buffer.WriteString(strconv.FormatFloat(x, 'f', 4, 64))
buffer.WriteString("\n")
// 将结果写入文件
f.WriteString(buffer.String()) 
英文:

I would like to know a simple and efficient way to print a table in Go. The solution I found works but it is really ugly.

many Thanks !

outfile := "file.tsv"
f, err := os.Create(outfile)
var buffer bytes.Buffer

buffer.WriteString(a[i])
buffer.WriteString("\t")
buffer.WriteString(a[j])
buffer.WriteString("\t")
buffer.WriteString(strconv.FormatFloat(x, 'f', 4, 64))
buffer.WriteString("\n")
// // write results to outfile
f.WriteString(buffer.String()) 

答案1

得分: 43

tabwriter 包是标准库中用于这种情况的简单易用的工具:

w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
fmt.Fprintln(w, "a\tb\tc\td\t")
fmt.Fprintln(w, "aa\tbb\tcc\t")
fmt.Fprintln(w, "aaa\tbbb\tccc\t")
fmt.Fprintln(w, "aaaa\tbbbb\tcccc\tdddd\t")
w.Flush()

// 输出结果:
// a    b    c    d 
// aa   bb   cc   
// aaa  bbb  ccc  
// aaaa bbbb cccc dddd 

你可以将 os.Stdout 替换为任何 io.Writer

英文:

The tabwriter package in the standard library is simple and easy for this kind of thing:

w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
fmt.Fprintln(w, "a\tb\tc\td\t")
fmt.Fprintln(w, "aa\tbb\tcc\t")
fmt.Fprintln(w, "aaa\tbbb\tccc\t")
fmt.Fprintln(w, "aaaa\tbbbb\tcccc\tdddd\t")
w.Flush()

// Prints out:
// a    b    c    d 
// aa   bb   cc   
// aaa  bbb  ccc  
// aaaa bbbb cccc dddd 

You can replace the os.Stdout with any io.Writer.

答案2

得分: 4

例如,

package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
)

func main() {
    outfile := "file.tsv"
    f, err := os.Create(outfile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer f.Close()
    w := csv.NewWriter(f)
    defer w.Flush()
    w.Comma = '\t'

    a := []string{"a", "b"}
    i, j := 0, 1
    x := float64(2.7)

    // 写入行
    err = w.Write(
        []string{
            a[i], a[j],
            strconv.FormatFloat(x, 'f', 4, 64),
        },
    )
    if err != nil {
        fmt.Println(err)
    }
}

输出:

$ cat file.tsv
a    b    2.7000
$

如果你使用goroutines,这是一个使用互斥锁保护csv.Writer的版本。

package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
    "sync"
)

type csvWriter struct {
    w *csv.Writer
    m sync.Mutex
}

func (c *csvWriter) write(rec []string) error {
    c.m.Lock()
    defer c.m.Unlock()
    return c.w.Write(rec)
}

func (c *csvWriter) flush() {
    c.m.Lock()
    defer c.m.Unlock()
    c.w.Flush()
}

func main() {
    outfile := "file.tsv"
    f, err := os.Create(outfile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer f.Close()
    w := csvWriter{w: csv.NewWriter(f)}
    defer w.flush()
    w.w.Comma = '\t'

    a := []string{"a", "b"}
    i, j := 0, 1
    x := float64(2.7)

    // 写入行
    err = w.write(
        []string{
            a[i], a[j],
            strconv.FormatFloat(x, 'f', 4, 64),
        },
    )
    if err != nil {
        fmt.Println(err)
    }
}
英文:

For example,

package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
)

func main() {
	outfile := "file.tsv"
	f, err := os.Create(outfile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer f.Close()
	w := csv.NewWriter(f)
	defer w.Flush()
	w.Comma = '\t'

	a := []string{"a", "b"}
	i, j := 0, 1
	x := float64(2.7)

	// Write row.
	err = w.Write(
		[]string{
			a[i], a[j],
			strconv.FormatFloat(x, 'f', 4, 64),
		},
	)
	if err != nil {
		fmt.Println(err)
	}
}

Output:

$ cat file.tsv
a	b	2.7000
$

If you use goroutines, here's a version that uses a mutex to protect the csv.Writer.

package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"sync"
)

type csvWriter struct {
	w *csv.Writer
	m sync.Mutex
}

func (c *csvWriter) write(rec []string) error {
	c.m.Lock()
	defer c.m.Unlock()
	return c.w.Write(rec)
}

func (c *csvWriter) flush() {
	c.m.Lock()
	defer c.m.Unlock()
	c.w.Flush()
}

func main() {
	outfile := "file.tsv"
	f, err := os.Create(outfile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer f.Close()
	w := csvWriter{w: csv.NewWriter(f)}
	defer w.flush()
	w.w.Comma = '\t'

	a := []string{"a", "b"}
	i, j := 0, 1
	x := float64(2.7)

	// Write row.
	err = w.write(
		[]string{
			a[i], a[j],
			strconv.FormatFloat(x, 'f', 4, 64),
		},
	)
	if err != nil {
		fmt.Println(err)
	}
}

答案3

得分: 2

选择一个现有的包可以简化你的代码,同时增加代码的可维护性。尝试使用go-pretty包。

+---------------------------------------------------------------------+
| Game of Thrones                                                     +
+-----+------------+-----------+--------+-----------------------------+
|   # | FIRST NAME | LAST NAME | SALARY |                             |
+-----+------------+-----------+--------+-----------------------------+
|   1 | Arya       | Stark     |   3000 |                             |
|  20 | Jon        | Snow      |   2000 | You know nothing, Jon Snow! |
| 300 | Tyrion     | Lannister |   5000 |                             |
+-----+------------+-----------+--------+-----------------------------+
|     |            | TOTAL     |  10000 |                             |
+-----+------------+-----------+--------+-----------------------------+
英文:

choose a exist package can simple your code and also increase code maintainability。try go-pretty

+---------------------------------------------------------------------+
| Game of Thrones                                                     +
+-----+------------+-----------+--------+-----------------------------+
|   # | FIRST NAME | LAST NAME | SALARY |                             |
+-----+------------+-----------+--------+-----------------------------+
|   1 | Arya       | Stark     |   3000 |                             |
|  20 | Jon        | Snow      |   2000 | You know nothing, Jon Snow! |
| 300 | Tyrion     | Lannister |   5000 |                             |
+-----+------------+-----------+--------+-----------------------------+
|     |            | TOTAL     |  10000 |                             |
+-----+------------+-----------+--------+-----------------------------+

huangapple
  • 本文由 发表于 2016年3月19日 20:09:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/36101534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定