GoCSV:将两个CSV列连接成一个单独的结构成员

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

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:&quot;colA&quot;`
	DateTime   string  // &lt;- like &quot;2017-04-14 09:50:10&quot;
	ColB       string `csv:&quot;colB&quot;`
}

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:&quot;colA&quot;`
    ColB       string `csv:&quot;colB&quot;`
    ColC       string `csv:&quot;colC&quot;`
}

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?

huangapple
  • 本文由 发表于 2017年4月14日 14:53:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/43406667.html
匿名

发表评论

匿名网友

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

确定