英文:
GoCSV: concatenate 2 csv columns into a single struct member
问题
你可以使用Go CSV库(https://github.com/gocarina/gocsv)将两个CSV列连接成一个结构体成员。
CSV格式如下所示:
colA, date, time, colB
A1, 2017-04-14, 09:50:10, B1
A2, 2017-04-14, 09:50:20, B2
你可以将这个CSV映射到以下结构体中:
type MyStruct struct {
ColA string `csv:"colA"`
DateTime string // <- 类似于 "2017-04-14 09:50:10"
ColB string `csv:"colB"`
}
你可以使用Go CSV或其他Go语言的方式来实现这个功能。
英文:
Can I concatenate 2 csv columns into a single struct member with Go CSV?
CSV format is like this.
colA, date, time, colB
A1, 2017-04-14, 09:50:10, B1
A2, 2017-04-14, 09:50:20, B2
I would like to map this CSV into the struct
type MyStruct struct {
ColA string `csv:"colA"`
DateTime string // <- like "2017-04-14 09:50:10"
ColB string `csv:"colB"`
}
How can I do this with Go CSV or another way in Go?
答案1
得分: 2
(a) 我认为没有支持的方法来实现这个。不过,你可以实现一个自定义的读取器,将字段合并到一起。虽然这是专有的,但我不建议这样做。
(b) 为什么不简单地在MyStruct中添加一个返回合并值的方法呢?
type MyStruct struct {
ColA string `csv:"colA"`
ColB string `csv:"colB"`
ColC string `csv:"colC"`
}
func (m MyStruct) dateTime() string {
return ColB+ColC
}
(c) 或许可以在解析之前使用一些 shell 命令对 CSV 进行预处理?
英文:
(a) I don't think there is a supported way to do this. However you could implement a custom reader that merges fields into each other. Rather proprietary, I wouldn't recommend it.
(b) Why not simply add a method to MyStruct that returns the merged values?
type MyStruct struct {
ColA string `csv:"colA"`
ColB string `csv:"colB"`
ColC string `csv:"colC"`
}
func (m MyStruct) dateTime() string {
return ColB+ColC
}
(c) Maybe use a little bit of shell-fu to pre-process the CSV before parsing it?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论