使用Golang获取CSV数据

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

Fetching CSV data using Golang

问题

如下所示,我已经读取了CSV文件并使用索引获取了数据。然后,我将标题名称与其相应的索引对齐。

现在,我该如何使用标题名称而不是索引从CSV文件中获取特定数据?我对Golang和编程都很陌生。

  1. func main() {
  2. file, ferr := os.Open("company1.csv")
  3. if ferr != nil {
  4. panic(ferr)
  5. }
  6. reader := csv.NewReader(file)
  7. reader.Comma = '|'
  8. reader.Comma = ','
  9. records, _ := reader.ReadAll()
  10. fmt.Println(records) // 打印所有记录
  11. fmt.Println("\n", records[1][0]) // 打印第一条记录
  12. fmt.Println("\n", records[0]) // 头部
  13. // 打印标题与索引
  14. index := 0
  15. for _, x := range records[0] {
  16. fmt.Println("\n", x, "-", index)
  17. index++
  18. }
  19. }

请注意,这只是读取CSV文件并打印数据的示例代码,并没有使用标题名称来获取特定数据。如果你想使用标题名称来获取数据,你需要编写逻辑来匹配标题名称并提取相应的数据。

英文:

As you can see below I have read the CSV file and also fetched data using the index. After that, I aligned the header name with its respective index.

Now, how can I fetch particular data from the CSV file using the header name and not the index? I'm new to Golang and programming.

  1. func main() {
  2. file, ferr := os.Open("company1.csv")
  3. if ferr != nil {
  4. panic(ferr)
  5. }
  6. reader := csv.NewReader(file)
  7. reader.Comma = '|'
  8. reader.Comma = ','
  9. records, _ := reader.ReadAll()
  10. fmt.Println(records) // prints all the records
  11. fmt.Println("\n",records[1][0]) //to print the first record
  12. fmt.Println("\n",records[0]) // header
  13. //to print the index along the header
  14. index := 0
  15. for _, x := range records[0] {
  16. fmt.Println("\n",x ,"-",index)
  17. index++
  18. }

答案1

得分: 4

创建一个从标题名称到列索引的映射。在索引记录时使用该映射:

  1. fields := make(map[string]int)
  2. for i, name := range records[0] {
  3. fields[name] = i
  4. }
  5. for _, record := range records[1:] {
  6. x := record[fields["name"]]
  7. fmt.Println(x)
  8. }

上述代码没有处理文件中缺少预期列的情况。在循环遍历数据记录之前,添加以下检查:

  1. for _, name := range []string{"name", "column2"} {
  2. if _, ok := fields[name]; !ok {
  3. log.Fatal("field missing:", name)
  4. }
  5. }
英文:

Create a map from header name to column index. Use that map when indexing a record:

  1. fields := make(map[string]int)
  2. for i, name := range records[0] {
  3. fields[name] = i
  4. }
  5. for _, record = range records[1:] {
  6. x = record[fields["name"]]
  7. fmt.Println(x)
  8. }

The above code does not handle the case where an expected column is missing from the file. Add this check before looping through the data records:

  1. for _, name := range []string{"name", "column2"} {
  2. if _, ok := fields[name]; !ok {
  3. log.Fatal("field missing", name)
  4. }
  5. }

huangapple
  • 本文由 发表于 2021年12月14日 03:12:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70339777.html
匿名

发表评论

匿名网友

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

确定