具有颜色属性的 golang 丝网印刷格式化数据

想要打印格式设置为典型 fmt 中的行/列表。Printf(“%5s %5s %5s\n”,col1, col2, col3)


如果字符串是纯文本,当然可以正常工作,但如果字符串具有颜色,粗体,字体等显示属性 - 即使可见数据与纯文本的长度相同,并且在%5s中也可以;做 len(col1) 要长得多,它会扭曲表对齐方式。


Printf有没有办法做到这一点,或者另一个std Go包?


要:


Item    Item   Item

=====   =====  ====

abc     defgh  xyz

x       abc    d

vv      xxxxx                 zz      <=== this happens if string xxxxx has display attributes from

                                            fatih,gchalk, etc. to set foreground/background color

`


//


包装主


import ( “fmt” “github.com/jwalton/gchalk” “github.com/fatih/color” )


func main() {


var colorWithGchalk = gchalk.Red

var data = []string{"one", "ten", "twenty"}


gchalk.SetLevel(gchalk.LevelAnsi16m) // seems needed for gitbash


// note output columns framed by <> just to see actual width


fmt.Println("desired formatted output")

fmt.Printf("<%-10s>  <%-10s>  <%-10s>\n\n", data[0],data[1],data[2])


/*

** gchalk

*/

// first try using gchalk for color

// colorize second column - column width ignored?

fmt.Println("colorized field loses its 10 character width, so subsequent fields now misaligned")

fmt.Printf("<%-10s>  <%-10s>  <%-10s>\n", data[0], colorWithGchalk(data[1]), data[2])


// same as above but eliminate gchalk function and just apply colorizing directly - same result

fmt.Printf("<%-10s>  <%-10s>  <%-10s>\n", data[0], gchalk.Red(data[1]), data[2])


/*

** fatih

*/


fmt.Println("\nwith fatih")

var colorWithFatih = color.New(color.FgRed).SprintFunc()

fmt.Printf("<%-10s>  <%-10s>  <%-10s>\n", data[0], colorWithFatih(data[1]), data[2])

} `


输出: ' 所需的格式化输出


彩色字段失去其 10 个字符的宽度,因此后续字段现在未对齐


与法提赫


' 在屏幕上,上面的 3 行根据需要以红色显示单词“10”,但字段不再为 10 宽。


料青山看我应如是
浏览 77回答 3
3回答

牧羊人nacy

Printf有没有办法做到这一点,不还是另一个标准 Go 包?不(你所谓的“显示属性”是字节输出流的一部分,它们不是“属性”,这是终端仿真器解释的“内联数据”。您可以做的是在打印之前过滤掉此内联数据。

小怪兽爱吃肉

您可以使用&nbsp;https://github.com/olekukonko/tablewriter&nbsp;作为如何输出表或仅使用包的示例。

慕标琳琳

在Jason Walton的建议下,Chalk to gchalk的搬运工。我得到了fmt。Printf %s 以满足我的需求,尽管如果字段宽度(%s)较窄,它们可能会出现问题。我想将至少两个字符串连接在一起以提供一个%s。第一个字符串是纯文本(sgCharToPrint),下一个字符串是彩色的,所以它是实际的屏幕文本(missedRaw)(错过的是颜色字符串,例如missueRaw用ansi格式字符包装。myLen = len(sgCharToPrint) + len(missedRaw)填充 = sgCharToPrint + missed + 字符串。重复(“ ”, 30 - olen)腾讯网.Printf(“%30s %4d %10s \n”,填充,值,尾部)现在,“表”显示保持对齐状态。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go