如何在Go中将一个CSV文件规范化(1:N)为一个映射?

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

how to normalize (1:N) a csv file to a map in Go?

问题

我正在尝试从一个CSV文件中规范化一个结构,它的格式如下:

name, note
'Joe', 5
'Joe', 3
'Ashley', 1
'Ashley', 7
'Ashley', 4

将其转换为一个映射,读取该文件后,将被简化为:

map [string][]string{
    "joe" = {5, 3},
    "ashley" = {1, 7, 4},
}

最好的方法是什么?

我是Go的新手,我创建的代码大致如下:

func main() {
    fileName := "new"
    xlsx, err := excelize.OpenFile(fileName + ".xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    rows, err := xlsx.Rows("Sheet1")
    if err != nil {
        fmt.Print(err)
    }

    for rows.Next() {

        column, err := rows.Columns()
        if err != nil {
            println(err)

        }

        for i := 0; i < 1; i++ {
            if i == i {
                m := map[string][]string{
                    column[i]: []string{column[1]},
                }
                fmt.Printf("%v\n", m)
            }

        }
    }
}
英文:

I'm trying to normalize a structure from a CSV file, which is like this:

name, note
&#39;Joe&#39;, 5
&#39;Joe&#39;, 3
&#39;Ashley&#39;, 1
&#39;Ashley&#39;, 7
&#39;Ashley&#39;, 4

to a map, that after read that file, will be reduced to:

map [string][]string{
    &quot;joe&quot; = {5, 3},
    &quot;ashley&quot; = {1, 7, 4},
}

what's the best approach to do that?

Im new in Go, and the code I created is something like this:

func main() {
	fileName := &quot;new&quot;
	xlsx, err := excelize.OpenFile(fileName + &quot;.xlsx&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	rows, err := xlsx.Rows(&quot;Sheet1&quot;)
	if err != nil {
		fmt.Print(err)
	}

	for rows.Next() {

		column, err := rows.Columns()
		if err != nil {
			println(err)

		}

		for i := 0; i &lt; 1; i++ {
			if i == i {
				m := map[string][]string{
					column[i]: []string{column[1]},
				}
				fmt.Printf(&quot;%v\n&quot;, m)
			}

		}
	}
}

答案1

得分: 1

应该相当简单:

m := map[string][]string{}
for rows.Next() {
    column, err := rows.Columns()
    if err != nil {
        panic(err)
    }
    if len(column) < 2 {
        panic("行太短")
    }
    m[column[0]] = append(m[column[0]], column[1])
}
英文:

It should be pretty straightforward:

m := map[string][]string{}
for rows.Next() {
    column, err := rows.Columns()
    if err != nil {
        panic(err)
    }
    if len(column) &lt; 2 {
        panic(&quot;row too short&quot;)
    }
    m[column[0]] = append(m[column[0]], column[1])
}

huangapple
  • 本文由 发表于 2022年12月7日 02:19:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/74707358.html
匿名

发表评论

匿名网友

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

确定